// components/footerLinks/Support.tsx
"use client";

import { Loader, Star, ChevronDown, Plus, X, RefreshCcw } from "lucide-react";
import Image from "next/image";
import React, { useEffect, useRef, useState } from "react";
import { useSelector } from "react-redux";
import { toast } from "sonner";
import { WebsiteFooter } from "@/components/website/WebsiteFooter";
import { addPublicSupport, getVerificationCaptcha, verifyCaptcha } from "@/lib/api/client";
import { WebsiteHeader } from "../website/WebsiteHeader";

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;

interface SupportProps {
  supportPageData: any;
  countryDataList: any[];
  logoImage: any;
}

const Support = ({ supportPageData, countryDataList, logoImage }: SupportProps) => {
  const [showCountryList, setShowCountryList] = useState(false);
  const [searchedCountry, setSearchedCountry] = useState("");
  const [selectedCountry, setSelectedCountry] = useState<any>(null);
  const [captchaData, setCaptchaData] = useState({ svg: "" });
  const [captchaInput, setCaptchaInput] = useState("");
  const [captchaError, setCaptchaError] = useState("");
  const countryDivRef = useRef<HTMLDivElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [loading, setLoading] = useState(false);
  const countryRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});
  const [uploadedFile, setUploadedFile] = useState<File | null>(null);
  const [supportData, setSupportData] = useState({
    fullName: "",
    phone: "",
    countryDetails: "",
    email: "",
    subject: "",
    description: "",
  });

  const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;

  const fetchCaptcha = async () => {
    try {
      const result = await getVerificationCaptcha(logoImage?.securityKey);
      if (result.success) {
        setCaptchaData({ svg: result.data.captcha });
      }
      setCaptchaInput("");
      setCaptchaError("");
    } catch (err) {
      console.error("Captcha fetch error:", err);
      toast.error("Failed to load CAPTCHA");
    }
  };

  const verifyCaptchaHandler = async (userCaptcha: string) => {
    try {
      const result = await verifyCaptcha({ captcha: userCaptcha }, logoImage?.securityKey);
      return result;
    } catch (err) {
      return { success: false, message: "Error verifying CAPTCHA" };
    }
  };

  const inputChangeHandler = (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = event.target;
    setSupportData((prevData) => {
      let newValue = value;
      if (name === "email") newValue = value.toLowerCase();
      if (name === "phone") newValue = value.replace(/[^0-9]/g, "");
      return { ...prevData, [name]: newValue };
    });
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      const allowedTypes = ["image/jpeg", "image/jpg", "image/png", "application/pdf"];
      const maxSize = 2 * 1024 * 1024;

      if (!allowedTypes.includes(file.type)) {
        toast.error("Only JPG, PNG, JPEG, and PDF files are allowed");
        event.target.value = "";
        return;
      }

      if (file.size > maxSize) {
        toast.error("File size must be less than 2 MB");
        event.target.value = "";
        return;
      }

      setUploadedFile(file);
    }
  };

  const handleRemoveFile = () => {
    setUploadedFile(null);
    if (fileInputRef.current) fileInputRef.current.value = "";
  };

  const handleAttachClick = () => {
    fileInputRef.current?.click();
  };

  const validateForm = () => {
    if (!supportData.fullName.trim()) {
      toast.error("Please enter your full name");
      return false;
    }
    if (!supportData.email.trim()) {
      toast.error("Please enter your email");
      return false;
    }
    if (!emailRegex.test(supportData.email)) {
      toast.error("Please enter a valid email address");
      return false;
    }
    if (!supportData.countryDetails) {
      toast.error("Please select a country");
      return false;
    }
    if (!supportData.phone.trim()) {
      toast.error("Please enter your phone number");
      return false;
    }
    if (supportData.phone.length < 10 || supportData.phone.length > 12) {
      toast.error("Phone number must be between 10 to 12 digits");
      return false;
    }
    if (!supportData.subject.trim()) {
      toast.error("Please enter a subject");
      return false;
    }
    if (!supportData.description.trim()) {
      toast.error("Please enter a description");
      return false;
    }
    if (!captchaInput) {
      setCaptchaError("Please enter CAPTCHA");
      return false;
    }
    return true;
  };

  const submitForm = async (event: React.FormEvent) => {
    event.preventDefault();

    if (!validateForm()) return;

    setLoading(true);

    try {
      const captchaResult = await verifyCaptchaHandler(captchaInput);

      if (!captchaResult.success) {
        toast.error(captchaResult.message || "CAPTCHA is incorrect!");
        fetchCaptcha();
        setLoading(false);
        return;
      }

      const formData = new FormData();
      formData.append("fullName", supportData.fullName);
      formData.append("phone", supportData.phone);
      formData.append("countryDetails", supportData.countryDetails);
      formData.append("email", supportData.email);
      formData.append("subject", supportData.subject);
      formData.append("description", supportData.description);

      if (uploadedFile) {
        formData.append("media", uploadedFile);
      }

      const result = await addPublicSupport(formData, logoImage?.securityKey);

      if (result?.success) {
        toast.success(result?.message);
        fetchCaptcha();
        setSupportData({
          fullName: "",
          phone: "",
          countryDetails: "",
          email: "",
          subject: "",
          description: "",
        });
        setSelectedCountry(null);
        setCaptchaInput("");
        setUploadedFile(null);
        if (fileInputRef.current) fileInputRef.current.value = "";
      } else {
        toast.error(result.message || "Failed to submit support request");
        fetchCaptcha();
      }
    } catch (error) {
      toast.error("An error occurred while submitting your request. Please try again.");
      fetchCaptcha();
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (countryDivRef.current && !countryDivRef.current.contains(event.target as Node)) {
        setShowCountryList(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  useEffect(() => {
    fetchCaptcha();
  }, []);

  const filteredCountries = countryDataList?.filter(
    (country) =>
      country.countryName.toLowerCase().includes(searchedCountry.toLowerCase()) ||
      country.countryCode.includes(searchedCountry)
  );

  const isFormValid =
    supportData.fullName &&
    supportData.email &&
    supportData.phone &&
    supportData.countryDetails &&
    supportData.subject &&
    supportData.description &&
    captchaInput;

  return (
    <div className="min-h-screen w-full flex flex-col">
              <WebsiteHeader headerData={supportPageData?.headerFooterImage} />

      {/* Main Content */}
      <div className="flex-1">
        <h1 className="text-3xl font-bold mt-5 text-black text-center">Support</h1>
        <form onSubmit={submitForm} className="max-w-md mx-auto flex flex-col gap-3 my-5 px-5">
          <div className="flex flex-col w-full">
            <div className="flex gap-0.5">
              <p className="text-[14px] text-[#333333] font-semibold leading-[24px]">Full Name</p>
              <Star className="w-2 h-2 mt-1 text-red-500" fill="currentColor" />
            </div>
            <input
              disabled={loading}
              autoComplete="off"
              type="text"
              name="fullName"
              value={supportData.fullName}
              onChange={inputChangeHandler}
              placeholder="Enter your full name"
              className="bg-white text-[14px] leading-[24px] placeholder:text-[14px] border-[1px] border-gray-300 py-[1px] px-2 rounded-md transition-all duration-300 ease-in-out focus:outline-none focus:border-[#0084a5] focus:shadow-[0_0_8px_0_rgba(0,132,165,0.3)]"
            />
          </div>

          <div className="flex flex-col w-full">
            <div className="flex gap-0.5">
              <p className="text-[14px] text-[#333333] leading-[24px]">Email</p>
              <Star className="w-2 h-2 mt-1 text-red-500" fill="currentColor" />
            </div>
            <input
              disabled={loading}
              autoComplete="off"
              type="email"
              name="email"
              value={supportData.email}
              onChange={inputChangeHandler}
              placeholder="Enter your email"
              className="bg-white text-[14px] leading-[24px] placeholder:text-[14px] border-[1px] border-gray-300 py-[1px] px-2 rounded-md transition-all duration-300 ease-in-out focus:outline-none focus:border-[#0084a5] focus:shadow-[0_0_8px_0_rgba(0,132,165,0.3)]"
            />
          </div>

          <div className="flex flex-col w-full relative" ref={countryDivRef}>
            <div className="flex gap-0.5">
              <p className="text-[12px] text-[#333333] leading-[22px]">Mobile</p>
              <Star className="w-2 h-2 mt-1 text-red-500" fill="currentColor" />
            </div>
            <div className="bg-white flex gap-3 items-center border-[1px] border-gray-300 rounded-md px-2 transition-all duration-300 ease-in-out focus-within:border-[#0084a5] focus-within:shadow-[0_0_8px_0_rgba(0,132,165,0.3)]">
              <div
                onClick={() => !loading && setShowCountryList(!showCountryList)}
                className="flex justify-between items-center w-16 cursor-pointer"
              >
                {selectedCountry ? (
                  <>
                    <Image
                      priority
                      quality={80}
                      width={24}
                      height={16}
                      src={`${BASE_URL}/uploads/${selectedCountry.countryFlag}`}
                      alt={selectedCountry.countryName}
                      className="w-6 h-4 object-cover"
                    />
                    <p className="text-[12px] text-[#333333] leading-[22px]">{selectedCountry.countryCode}</p>
                  </>
                ) : (
                  <>
                    <p className="text-[12px] text-gray-400 leading-[22px]">Select</p>
                    <ChevronDown className={`w-3 h-3 text-gray-600 transition-transform duration-200 ${showCountryList ? "rotate-180" : ""}`} />
                  </>
                )}
              </div>
              <div className="w-[1px] h-6 bg-gray-300"></div>
              <input
                disabled={loading || !selectedCountry}
                autoComplete="off"
                type="tel"
                name="phone"
                value={supportData.phone}
                onChange={inputChangeHandler}
                placeholder="e.g., 1234567890"
                maxLength={12}
                className="w-full border-none outline-none py-[1px] text-[12px] leading-[22px] placeholder:text-[12px]"
              />
            </div>
            {showCountryList && (
              <div className="absolute top-full w-24 left-0 right-0 mt-1 bg-white border-[1px] border-gray-300 rounded-md shadow-lg z-10 max-h-60 overflow-hidden">
                <div className="p-1 border-b border-gray-300">
                  <input
                    type="text"
                    placeholder="Search..."
                    value={searchedCountry}
                    onChange={(e) => setSearchedCountry(e.target.value)}
                    className="w-full px-1 py-1 text-[12px] border-[1px] border-gray-300 rounded-md focus:outline-none focus:border-[#0084a5]"
                  />
                </div>
                <div className="overflow-y-auto max-h-48">
                  {filteredCountries?.map((country: any) => (
                    <div
                      key={country._id}
                      ref={(el) => {
                        countryRefs.current[country._id] = el;
                      }}
                      onClick={() => {
                        setSelectedCountry(country);
                        setSupportData((prev) => ({ ...prev, countryDetails: country._id }));
                        setShowCountryList(false);
                        setSearchedCountry("");
                      }}
                      className="flex gap-1 items-center px-1.5 py-0.5 hover:bg-gray-100 cursor-pointer transition-colors"
                    >
                      <Image
                        priority
                        quality={80}
                        width={24}
                        height={16}
                        src={`${BASE_URL}/uploads/${country.countryFlag}`}
                        alt={country.countryName}
                        className="w-5 h-4 object-cover"
                      />
                      <p className="text-[12px] text-[#333333] leading-[22px]">{country.countryCode}</p>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>

          <div className="flex flex-col w-full">
            <div className="flex gap-0.5">
              <p className="text-[14px] text-[#333333] leading-[24px]">Subject</p>
              <Star className="w-2 h-2 mt-1 text-red-500" fill="currentColor" />
            </div>
            <input
              disabled={loading}
              autoComplete="off"
              type="text"
              name="subject"
              value={supportData.subject}
              onChange={inputChangeHandler}
              placeholder="Enter your subject"
              className="bg-white text-[14px] leading-[24px] placeholder:text-[14px] border-[1px] border-gray-300 py-[1px] px-2 rounded-md transition-all duration-300 ease-in-out focus:outline-none focus:border-[#0084a5] focus:shadow-[0_0_8px_0_rgba(0,132,165,0.3)]"
            />
          </div>

          <div className="flex flex-col w-full">
            <div className="flex gap-0.5">
              <p className="text-[14px] text-[#333333] leading-[24px]">Description</p>
              <Star className="w-2 h-2 mt-1 text-red-500" fill="currentColor" />
            </div>
            <textarea
              rows={4}
              disabled={loading}
              name="description"
              value={supportData.description}
              onChange={inputChangeHandler}
              placeholder="Enter your description"
              className="resize-none bg-white text-[14px] leading-[24px] placeholder:text-[14px] border-[1px] border-gray-300 py-[1px] px-2 rounded-md transition-all duration-300 ease-in-out focus:outline-none focus:border-[#0084a5] focus:shadow-[0_0_8px_0_rgba(0,132,165,0.3)]"
            />
          </div>

          <input ref={fileInputRef} type="file" accept=".jpg,.jpeg,.png,.pdf" onChange={handleFileChange} className="hidden" />

          {!uploadedFile ? (
            <div onClick={handleAttachClick} className="flex items-center cursor-pointer">
              <div className="w-7 h-7 flex justify-center items-center">
                <Plus className="text-black w-5 h-5" />
              </div>
              <p className="text-[14px] text-[#333333] font-semibold leading-[24px]">Attach File</p>
              <p className="ml-1 text-[12px] text-[#006d8a] font-semibold leading-[22px]">(only pdf and image 2 MB)</p>
            </div>
          ) : (
            <div className="flex items-center justify-between bg-gray-100 border-[1px] border-gray-300 rounded-md px-2 py-2">
              <p className="text-[14px] text-[#333333] leading-[24px] truncate flex-1">{uploadedFile.name}</p>
              <button type="button" onClick={handleRemoveFile} className="w-7 h-7 flex items-center justify-center cursor-pointer">
                <X className="w-5 h-5 text-red-500 hover:text-red-600 transition-all hover:scale-110" />
              </button>
            </div>
          )}

          <div className="flex flex-col w-full">
            <div className="flex gap-0.5">
              <p className="text-[12px] text-[#333333] leading-[22px]">CAPTCHA</p>
              <Star className="w-2 h-2 mt-1 text-red-500" fill="currentColor" />
            </div>
            <div className="flex justify-between w-full items-center">
              <div className="flex gap-1 w-full items-center">
                <div dangerouslySetInnerHTML={{ __html: captchaData.svg }} />
                <input
                  disabled={loading}
                  type="text"
                  value={captchaInput}
                  onChange={(e) => {
                    setCaptchaInput(e.target.value);
                    setCaptchaError("");
                  }}
                  placeholder="?"
                  className="bg-white text-center text-[12px] leading-[22px] placeholder:text-[12px] w-10 placeholder:leading-[22px] placeholder:text-gray-400 py-[1px] px-2 rounded-md transition-all duration-300 ease-in-out focus:outline-none focus:border-[#0084a5] focus:shadow-[0_0_8px_0_rgba(0,132,165,0.3)] border-[1px] border-gray-300"
                />
                <button
                  type="button"
                  onClick={fetchCaptcha}
                  className="flex cursor-pointer items-center justify-center w-6 h-6 bg-gray-200 rounded-md"
                >
                  <RefreshCcw className="w-3 h-3 text-black" />
                </button>
              </div>
            </div>
            {captchaError && <p className="text-red-500 text-xs mt-1">{captchaError}</p>}
          </div>

          <button
            disabled={loading || !isFormValid}
            type="submit"
            className={`text-white ${
              isFormValid && !loading ? "bg-[#0084a5] cursor-pointer hover:bg-[#006d8a]" : "bg-gray-600 cursor-not-allowed"
            } rounded-md w-full py-2 text-[14px] flex items-center justify-center leading-[24px] font-semibold transition-colors duration-300`}
          >
            {loading ? <Loader className="w-6 h-6 text-white animate-spin" /> : "Submit"}
          </button>
        </form>
      </div>

      {/* Footer */}
      <WebsiteFooter footerData={supportPageData?.headerFooterImage} socialLinks={supportPageData?.socialLinks} />
    </div>
  );
};

export default Support;