"use client";

import useAxios from "@/hooks/useAxios";
import { useEffect, useRef, useState } from "react";
import SafeHtmlRenderer from "../SafeHtmlRenderer";
import { RefreshCw } from "lucide-react";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

const requiredFields = [
  "firstName",
  "email",
  "phone",
  "organizationName",
  "streetAddress",
  "country",
  "captcha",
  "website",
];

export default function GlaApply({ table }: any) {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const modalRef = useRef<HTMLDivElement>(null);

  const [formData, setFormData] = useState({
    firstName: "",
    lastName: "",
    email: "",
    phone: "",
    organizationName: "",
    streetAddress: "",
    aptUnit: "",
    country: "",
    website: "",
    aboutOrganisation: "",
    organizationProfile: "",
    expert: "",
    captcha: "",
    sourcePage: "",
  });

  const [captchaSvg, setCaptchaSvg] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [countryDropdown, setCountryDropdown] = useState<any[]>([]);
  const { postData, getData } = useAxios();

  useEffect(() => {
    const pathname = window.location.pathname;
    const lastSegment = pathname.split("/").filter(Boolean).pop();

    const mapping = {
      accreditationbody: "Accreditation Body",
      certificationbody: "Certification Body",
      personnelcertificationbody: "Personnel Certification Body",
      gla: "GLA",
    };

    const mappedValue =
      mapping[lastSegment as keyof typeof mapping] ||
      lastSegment ||
      "SourcePage";

    setFormData((prev) => ({
      ...prev,
      sourcePage: mappedValue,
    }));
  }, []);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        modalRef.current &&
        !modalRef.current.contains(event.target as Node)
      ) {
        setIsModalOpen(false);
      }
    };

    if (isModalOpen) {
      fetchCaptcha();
      fetchAllCountries();
      document.addEventListener("mousedown", handleClickOutside);
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isModalOpen]);

  const fetchCaptcha = async () => {
    try {
      const { data }: any = await getData("captcha/generateCaptcha", {
        withCredentials: true,
      });
      setCaptchaSvg(data?.captcha);
    } catch (error) {
      toast.error("Failed to fetch captcha");
    }
  };

  const fetchAllCountries = async () => {
    try {
      const { data }: any = await getData("dropdown/getAllCountry");
      setCountryDropdown(data || []);
    } catch (error) {
      toast.error("Failed to fetch countries");
    }
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    // Country validation - check if country name exists
    const selectedCountry = countryDropdown.find(
      (c) => c.billcountryid === formData.country
    );

    if (!selectedCountry) {
      toast.error("Please select a country");
      return;
    }

    const missingFields = requiredFields.filter(
      (field) => !formData[field as keyof typeof formData]?.trim()
    );

    if (missingFields.length > 0) {
      toast.error(`Please fill the required field: ${missingFields[0]}`);
      return;
    }

    setIsSubmitting(true);

    try {
      const submitData = {
        ...formData,
        country: selectedCountry.billcountry, // ✅ Send country name instead of ID
      };

      const response: any = await postData("organization_details", submitData, {
        withCredentials: true,
      });

      if (response?.success) {
        toast.success(response?.message || "Submitted successfully!");
        setFormData({
          firstName: "",
          lastName: "",
          email: "",
          phone: "",
          organizationName: "",
          streetAddress: "",
          aptUnit: "",
          country: "",
          website: "",
          aboutOrganisation: "",
          organizationProfile: "",
          expert: "",
          captcha: "",
          sourcePage: "main-application-page",
        });
        fetchCaptcha();
      } else {
        if (response?.message?.toLowerCase()?.includes("captcha")) {
          toast.error("Captcha is incorrect. Please try again.");
        } else {
          toast.error(response?.message || "Submission failed.");
        }
        fetchCaptcha();
      }
    } catch (error) {
      toast.error("Something went wrong. Please try again.");
      fetchCaptcha();
    } finally {
      setIsSubmitting(false);
    }
  };

  const updateField = (field: string, value: string) => {
    if (["firstName", "lastName", "organizationName"].includes(field)) {
      value = value.replace(/[^a-zA-Z\s]/g, "");
    }
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  return (
    <>
      <ToastContainer position="top-right" autoClose={3000} />
      <div className="flex w-40 rounded-lg bg-btn p-0.5 shadow-lg">
        <button
          onClick={() => setIsModalOpen(true)}
          className="flex-1 font-normal text-md bg-white/90 px-6 py-3 hover:scale-105 rounded-lg hover:-translate-y-2 transition duration-500 items-center flex justify-center"
        >
          <span>Apply Here</span>
        </button>
      </div>

      {isModalOpen && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 px-4">
          <div
            ref={modalRef}
            className="relative bg-white rounded-lg shadow-lg p-6 h-[500px] md:w-[67%] w-[100%] overflow-y-scroll"
          >
            <button
              onClick={() => setIsModalOpen(false)}
              className="absolute top-2 right-5 text-gray-500 hover:text-gray-800 text-xl"
            >
              &times;
            </button>

            <h2 className="text-xl font-bold mb-4 text-center">
              Application Form
            </h2>

            <form onSubmit={handleSubmit}>
              <h2 className="text-lg font-medium mb-4">Organization Details</h2>
              <div className="grid md:grid-cols-2 gap-4">
                <Input
                  label="Organization Name"
                  name="organizationName"
                  value={formData.organizationName}
                  onChange={updateField}
                />
                <Input
                  label="Street Address"
                  name="streetAddress"
                  value={formData.streetAddress}
                  onChange={updateField}
                />
                <Input
                  label="Apt/Unit"
                  name="aptUnit"
                  value={formData.aptUnit}
                  onChange={updateField}
                />

                {/* ✅ Country Dropdown - Store ID but display name */}
                <div>
                  <label
                    htmlFor="country"
                    className="block text-sm font-medium text-gray-700"
                  >
                    Country <span className="text-red-600">*</span>
                  </label>
                  <select
                    id="country"
                    name="country"
                    value={formData.country}
                    onChange={(e) => updateField("country", e.target.value)}
                    className="mt-1 block w-full px-4 py-2 text-gray-700 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300"
                  >
                    <option value="">Select Country</option>
                    {countryDropdown?.map((c: any) => (
                      <option key={c.billcountryid} value={c.billcountryid}>
                        {c.billcountry}
                      </option>
                    ))}
                  </select>
                </div>

                <Input
                  label="Website"
                  name="website"
                  value={formData.website}
                  onChange={updateField}
                />
              </div>

              <h2 className="text-lg font-medium mt-6 mb-4">
                Contact Person Details
              </h2>
              <div className="grid md:grid-cols-2 gap-4">
                <Input
                  label="First Name"
                  name="firstName"
                  value={formData.firstName}
                  onChange={updateField}
                />
                <Input
                  label="Last Name"
                  name="lastName"
                  value={formData.lastName}
                  onChange={updateField}
                />
                <Input
                  label="Email"
                  name="email"
                  type="email"
                  value={formData.email}
                  onChange={updateField}
                />
                <Input
                  label="Phone"
                  name="phone"
                  type="tel"
                  value={formData.phone}
                  onChange={updateField}
                />
              </div>

              <Textarea
                label="About Organisation Activities / Service"
                name="aboutOrganisation"
                value={formData.aboutOrganisation}
                onChange={updateField}
              />
              <Textarea
                label="Organization Profile"
                name="organizationProfile"
                value={formData.organizationProfile}
                onChange={updateField}
              />
              <Textarea
                label="Apply Scope Detail:"
                name="expert"
                value={formData.expert}
                onChange={updateField}
              />

              {/* ✅ Chhota Captcha Section */}
              <div className="my-4">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Captcha <span className="text-red-600">*</span>
                </label>
                <div className="flex items-center space-x-3">
                  {/* Captcha Image - Chhota kiya */}
                  <input
                    type="text"
                    className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 sm:text-sm max-w-[200px]"
                    value={formData.captcha}
                    onChange={(e) => updateField("captcha", e.target.value)}
                    placeholder="Enter captcha"
                  />
                  <div className="flex-shrink-0 border rounded p-1 bg-gray-50">
                    <SafeHtmlRenderer
                      htmlContent={captchaSvg}
                      // className="h-8"
                    />
                  </div>

                  {/* Refresh Button */}
                  <button
                    type="button"
                    onClick={fetchCaptcha}
                    className="p-1 rounded-full hover:bg-gray-200 transition-colors"
                    aria-label="Regenerate Captcha"
                  >
                    <RefreshCw className="w-4 h-4" /> {/* ✅ Chhota icon */}
                  </button>

                  {/* Captcha Input - Compact */}
                </div>
              </div>

              <div className="text-center my-4">
                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="hover:bg-btnhover hover:scale-105 px-6 py-2 border border-transparent text-sm font-medium rounded-full text-black bg-btn transition-all duration-300"
                >
                  {isSubmitting ? "Submitting..." : "Submit"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </>
  );
}

// Input and Textarea components remain same...
function Input({
  label,
  name,
  value,
  onChange,
  type = "text",
}: {
  label: string;
  name: string;
  value: string;
  onChange: (field: string, value: string) => void;
  type?: string;
}) {
  const isRequired = requiredFields.includes(name);
  return (
    <div>
      <label htmlFor={name} className="block text-sm font-medium text-gray-700">
        {label} {isRequired && <span className="text-red-600">*</span>}
      </label>
      <input
        id={name}
        name={name}
        type={type}
        placeholder={label}
        value={value}
        onChange={(e) => onChange(name, e.target.value)}
        className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 sm:text-sm"
      />
    </div>
  );
}

function Textarea({
  label,
  name,
  value,
  onChange,
}: {
  label: string;
  name: string;
  value: string;
  onChange: (field: string, value: string) => void;
}) {
  return (
    <div className="my-4">
      <label htmlFor={name} className="block text-sm font-medium text-gray-700">
        {label}
      </label>
      <textarea
        id={name}
        name={name}
        rows={4}
        placeholder={label}
        value={value}
        onChange={(e) => onChange(name, e.target.value)}
        className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 sm:text-sm"
      ></textarea>
    </div>
  );
}
