"use client";

import { useState, useEffect } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { X } from "lucide-react";
import {
  defaultScrollPopupConfig,
  type ScrollPopupConfig,
} from "@/lib/scrollPopupDefaults";

export default function ScrollPopup() {
  const [showPopup, setShowPopup] = useState(false);
  const [closed, setClosed] = useState(false);
  const [phone, setPhone] = useState("");
  const [status, setStatus] = useState("");
  const [loading, setLoading] = useState(false);
  const [popupConfig, setPopupConfig] = useState<ScrollPopupConfig>(
    defaultScrollPopupConfig
  );

  useEffect(() => {
    const handleScroll = () => {
      if (window.scrollY > 300 && !closed) {
        setShowPopup(true);
      }
    };

    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, [closed]);

  useEffect(() => {
    let timeout: NodeJS.Timeout;
    if (closed) {
      timeout = setTimeout(() => {
        setClosed(false);
        setShowPopup(true);
      }, 30000); // 30 seconds
    }
    return () => clearTimeout(timeout);
  }, [closed]);

  useEffect(() => {
    const loadPopupConfig = async () => {
      try {
        const res = await fetch("/api/scrollpopup", { cache: "no-store" });
        if (!res.ok) return;

        const data = (await res.json()) as { config?: Partial<ScrollPopupConfig> };
        if (data?.config) {
          setPopupConfig((prev) => ({ ...prev, ...data.config }));
        }
      } catch (error) {
        console.error("Failed to load scroll popup config:", error);
      }
    };

    loadPopupConfig();
  }, []);

  const handleSubmit = async () => {
    if (!phone.trim()) {
      setStatus("Please enter a valid phone number.");
      return;
    }

    setLoading(true);
    setStatus("");

    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: "Popup offer mobile submission",
          phone,
          email: "apply@banksfinders.com",
          message: "User submitted mobile number from popup form.",
        }),
      });

       await res.json();
      if (res.ok) {
        setStatus("Thank you! We will contact you soon.");
        setPhone("");
      } else {
        setStatus("Submission failed. Please try again.");
      }
    } catch (error) {
      setStatus(`Something went wrong. ${error}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div
      className={`fixed bottom-0 left-0 w-full p-0 transition-all duration-500 ${
        showPopup ? "opacity-100 translate-y-0" : "opacity-0 translate-y-full"
      }`}
    >
      {showPopup && (
<Card className="w-full bg-blue-500 shadow-lg relative rounded-none min-h-[56px] flex items-center px-4 overflow-hidden">
  <button
    className="absolute top-2 right-2 text-gray-200 hover:text-white"
    onClick={() => {
      setClosed(true);
      setShowPopup(false);
    }}
    aria-label="Close popup"
  >
    <X size={20} />
  </button>

  <CardContent className="flex flex-col md:flex-row items-center justify-between w-full max-w-6xl mx-auto px-0 space-y-1 md:space-y-0">
    <div className="flex flex-col md:flex-row md:items-center space-y-0.5 md:space-y-0 md:space-x-3 text-center md:text-left text-white">
      <h2 className="text-sm font-semibold md:text-lg leading-tight">
        {popupConfig.titleText}
      </h2>
      <p className="text-xs md:text-lg leading-tight">
        {popupConfig.subtitleText}
      </p>
    </div>

    <div className="w-full md:w-auto">
      <div className="flex flex-col sm:flex-row items-center space-y-1 sm:space-y-0 sm:space-x-2 mt-4">
        <input
          type="text"
          value={phone}
          onChange={(e) => setPhone(e.target.value)}
          placeholder={popupConfig.phonePlaceholder}
          className="w-full sm:w-56 p-1.5 text-sm border border-gray-300 rounded-md text-center sm:text-left"
          style={{ boxSizing: "border-box" }}
        />
        <Button
          className="bg-red-600 text-white px-4 py-1.5 w-full sm:w-auto text-sm"
          onClick={handleSubmit}
          disabled={loading}
        >
          {loading ? "Sending..." : popupConfig.submitButtonText}
        </Button>
      </div>
      {status && (
        <p className="text-xs text-white mt-1 ml-1">{status}</p>
      )}
      <p className="text-xs text-gray-200 mt-1 ml-1">
        {popupConfig.termsUrl ? (
          <a
            href={popupConfig.termsUrl}
            className="underline underline-offset-2 hover:text-white"
            target={popupConfig.termsUrl.startsWith("http") ? "_blank" : undefined}
            rel={popupConfig.termsUrl.startsWith("http") ? "noreferrer" : undefined}
          >
            {popupConfig.termsText}
          </a>
        ) : (
          popupConfig.termsText
        )}
      </p>
    </div>
  </CardContent>
</Card>


      )}
    </div>
  );
}
