"use client";

import { BASE_URL } from "@/Constant";
import axios from "axios";
import React, { useEffect, useState, useRef } from "react";
import { toast, ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import useAxios from "@/hooks/useAxios";
import SafeHtmlRenderer from "../SafeHtmlRenderer";
import { RefreshCw, Eye, EyeOff, Loader2 } from "lucide-react";

const mendatoryField: any = {
  oFullName: "Organisation Full Name",
  oRegistrationDate: "Organisation Registration Date",
  cFirstName: "Customer First Name",
  cPhone: "Customer Phone",
  sDate: "Signature Date",
  signature: "Signature upload",
  clientLogo: "Company Logo",
  password: "Password",
  cpassword: "Confirm Password",
  cEmail: "Email",
};

function checkErrorBeforSend(data: any) {
  const {
    oFullName,
    oRegistrationDate,
    cFirstName,
    cPhone,
    sDate,
    signature,
    clientLogo,
    password,
    cpassword,
    cEmail,
  } = data;

  const requiredFields = {
    oFullName,
    oRegistrationDate,
    cFirstName,
    cPhone,
    sDate,
    signature,
    clientLogo,
    password,
    cpassword,
    cEmail,
  };

  const missingFields = Object.entries(requiredFields)
    .filter(
      ([key, value]) => value === undefined || value === null || value === ""
    )
    .map(([key]) => mendatoryField[key]);

  return missingFields;
}

export default function AssociationForm() {
  const [countryDropdown, setCountryDropdown] = useState([]);
  const [stateDropdown, setStateDropdown] = useState([]);
  const [cityDropdown, setCityDropdown] = useState([]);
  const [captchaSvg, setCaptchaSvg] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false); // Loading state
  const { getData } = useAxios();

  // Empty references array se start karo
  const [references, setReferences] = useState<any[]>([]);

  const signatureInputRef = useRef<HTMLInputElement | null>(null);
  const clientLogoInputRef = useRef<HTMLInputElement | null>(null);

  const [formData, setFormData] = useState<{
    password: string;
    cpassword: string;
    signature: File | null;
    clientLogo: File | null;
    oCountry: string;
    oFullName: string;
    oRegistrationDate: string;
    oStreetAddress: string;
    oAptUnit: string;
    website: string;
    cFirstName: string;
    cLastName: string;
    lEmail: string;
    cDate: string;
    cStreetAddress: string;
    cAptUnit: string;
    cCity: string;
    cState: string;
    cZipcode: string;
    cPhone: string;
    cEmail: string;
    aboutOrganisation: string;
    organisationProfile: string;
    expert: string;
    sDate: string;
    captcha: string;
  }>({
    oFullName: "",
    oRegistrationDate: "",
    oStreetAddress: "",
    oAptUnit: "",
    oCountry: "",
    website: "",
    cFirstName: "",
    cLastName: "",
    lEmail: "",
    cDate: "",
    cStreetAddress: "",
    cAptUnit: "",
    cCity: "",
    cState: "",
    cZipcode: "",
    cPhone: "",
    cEmail: "",
    aboutOrganisation: "",
    organisationProfile: "",
    expert: "",
    signature: null,
    clientLogo: null,
    sDate: "",
    captcha: "",
    password: "",
    cpassword: "",
  });

  // Add reference function
  const addReference = () => {
    const newReference = {
      rFullName: "",
      expertiseFor: "",
      qualificationAndExperience: "",
      rPhone: "",
      rAddress: "",
      rEmail: "",
      _id: Date.now().toString(),
    };
    setReferences([...references, newReference]);
  };

  // Remove reference function
  const removeReference = (index: number) => {
    setReferences(references.filter((_, i) => i !== index));
  };

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleReferenceChange = (
    index: number,
    field: string,
    value: string
  ) => {
    setReferences((prev) => {
      const updated = [...prev];
      updated[index] = { ...updated[index], [field]: value };
      return updated;
    });
  };

  const fetchAllCountries = async () => {
    try {
      const { data } = await axios.get(`${BASE_URL}dropdown/getAllCountry`);
      setCountryDropdown(data?.data);
    } catch (error) {
      console.log(error);
    }
  };

  const fetchAllStates = async (code: any) => {
    try {
      const { data } = await axios.get(
        `${BASE_URL}dropdown/getAllStates?billcountryid=${code}`
      );
      setStateDropdown(data?.data);
    } catch (error) {
      console.log(error);
    }
  };

  const fetchAllCities = async (code: any) => {
    try {
      const { data } = await axios.get(
        `${BASE_URL}dropdown/getAllCity?billstateid=${code}`
      );
      setCityDropdown(data?.data);
    } catch (error) {
      console.log(error);
    }
  };

  const fetchCaptcha = async () => {
    try {
      const { data }: any = await getData("captcha/generateCaptcha", {
        withCredentials: true,
      });
      setCaptchaSvg(data?.captcha);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    fetchAllCountries();
    fetchCaptcha();
  }, []);

  useEffect(() => {
    if (formData?.oCountry) {
      fetchAllStates(formData.oCountry);
    }
  }, [formData.oCountry]);

  useEffect(() => {
    if (formData.cState) {
      fetchAllCities(formData.cState);
    }
  }, [formData.cState]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const filteredReferences = references.filter((ref) =>
      Object.entries(ref).some(
        ([key, value]) =>
          key !== "_id" && typeof value === "string" && value.trim() !== ""
      )
    );

    try {
      if (formData.password !== formData.cpassword) {
        toast.error("Password and Confirm Password Does not match!");
        setIsSubmitting(false);
        return;
      }

      if (formData.password.length < 6) {
        toast.error("Password must be at least 6 characters long!");
        setIsSubmitting(false);
        return;
      }

      const missingFields = checkErrorBeforSend(formData);

      if (missingFields.length > 0) {
        toast.error(`Required Fields are: ${missingFields.join(", ")}`);
        setIsSubmitting(false);
        return;
      }

      const formDataToSend = new FormData();

      for (const key in formData) {
        const value = formData[key as keyof typeof formData];
        if ((key === "signature" || key === "clientLogo") && value) {
          formDataToSend.append(key, value);
        } else {
          formDataToSend.append(key, String(value || ""));
        }
      }

      formDataToSend.append("references", JSON.stringify(filteredReferences));

      const loadingToast = toast.loading("Submitting your application...");

      const response = await axios.post(
        `${BASE_URL}association-member/withoutLogin`,
        formDataToSend,
        {
          headers: {
            "Content-Type": "multipart/form-data",
          },
          withCredentials: true,
        }
      );

      toast.dismiss(loadingToast);

      if (response.data.success) {
        toast.success(
          response.data.message || "Application submitted successfully!"
        );

        setFormData({
          password: "",
          cpassword: "",
          oFullName: "",
          oRegistrationDate: "",
          oStreetAddress: "",
          oAptUnit: "",
          oCountry: "",
          website: "",
          cFirstName: "",
          cLastName: "",
          lEmail: "",
          cDate: "",
          cStreetAddress: "",
          cAptUnit: "",
          cCity: "",
          cState: "",
          cZipcode: "",
          cPhone: "",
          cEmail: "",
          aboutOrganisation: "",
          organisationProfile: "",
          expert: "",
          signature: null,
          clientLogo: null,
          sDate: "",
          captcha: "",
        });

        // Reset the references
        setReferences([]);

        // Clear the signature file input
        if (signatureInputRef.current) {
          signatureInputRef.current.value = "";
        }

        // Clear the clientLogo file input
        if (clientLogoInputRef.current) {
          clientLogoInputRef.current.value = "";
        }

        // Reload captcha
        fetchCaptcha();
      } else {
        toast.warning(response.data.message || "Something went wrong!");
      }
    } catch (error: any) {
      console.error("Submission Error:", error);

      // Dismiss any loading toasts if present
      toast.dismiss();

      toast.error(
        error?.response?.data?.message || "An error occurred during submission."
      );

      if (error?.response?.data?.message === "Captcha problem again enter") {
        // toast.info("Please enter captcha again");
        fetchCaptcha();
      }
    } finally {
      // Loading state end
      setIsSubmitting(false);
    }
  };

  return (
    <div className="max-w-4xl mx-auto my-12 shadow-md rounded-lg overflow-hidden">
      <div className="px-4 py-5 sm:p-6 bg-white/25">
        <div className="text-center mb-6">
          <h1 className="text-2xl font-bold text-gray-900">Membership Form</h1>
          <p className="text-sm text-gray-600 mt-1">
            MEMBERSHIP SCHEME FOR ASSOCIATION MEMBERS
          </p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-8">
          {/* Organization details */}
          <div>
            <h2 className="text-lg font-medium text-gray-900 mb-4">
              Organisation Details
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label
                  htmlFor="oFullName"
                  className="block text-sm font-medium text-gray-700"
                >
                  Organisation Name: <span className="text-red-600">*</span>
                </label>
                <input
                  type="text"
                  id="oFullName"
                  name="oFullName"
                  value={formData.oFullName}
                  onChange={handleChange}
                  placeholder="Organisation Name"
                  className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                />
              </div>
              <div>
                <label
                  htmlFor="oRegistrationDate"
                  className="block text-sm font-medium text-gray-700"
                >
                  Organisation Registration Date:{" "}
                  <span className="text-red-600">*</span>
                </label>
                <input
                  type="date"
                  onKeyDown={(e) => e.preventDefault()}
                  id="oRegistrationDate"
                  name="oRegistrationDate"
                  value={formData.oRegistrationDate}
                  onChange={handleChange}
                  className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                />
              </div>

              {/* Client Logo Field */}
              <div>
                <label
                  htmlFor="clientLogo"
                  className="block text-sm font-medium text-gray-700"
                >
                  Company Logo: <span className="text-red-600">*</span>
                </label>
                <input
                  type="file"
                  name="clientLogo"
                  id="clientLogo"
                  accept="image/*"
                  ref={clientLogoInputRef}
                  className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  onChange={(e) => {
                    if (e.target.files && e.target.files[0]) {
                      setFormData({
                        ...formData,
                        clientLogo: e.target.files[0] || null,
                      });
                    }
                  }}
                />
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
              <div>
                <label
                  htmlFor="oStreetAddress"
                  className="block text-sm font-medium text-gray-700"
                >
                  Address:
                </label>
                <input
                  type="text"
                  id="oStreetAddress"
                  name="oStreetAddress"
                  value={formData.oStreetAddress}
                  onChange={handleChange}
                  className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="Street Address"
                />
              </div>
              <div>
                <label
                  htmlFor="oAptUnit"
                  className="block text-sm font-medium text-gray-700"
                >
                  Apt/Unit:
                </label>
                <input
                  type="text"
                  id="oAptUnit"
                  name="oAptUnit"
                  value={formData.oAptUnit}
                  onChange={handleChange}
                  className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="Apt/Unit #"
                />
              </div>
              <div>
                <label
                  htmlFor="oCountry"
                  className="block text-sm font-medium text-gray-700"
                >
                  Country
                </label>
                <select
                  id="oCountry"
                  name="oCountry"
                  value={formData.oCountry}
                  onChange={(e) => {
                    setFormData({
                      ...formData,
                      oCountry: (e.target as HTMLSelectElement).value,
                    });
                  }}
                  className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                >
                  <option value="">Select Country</option>
                  {countryDropdown.map((oCountry: any) => (
                    <option
                      key={oCountry.billcountryid}
                      value={oCountry.billcountryid}
                    >
                      {oCountry.billcountry}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label
                  htmlFor="website"
                  className="block text-sm font-medium text-gray-700"
                >
                  Website:
                </label>
                <input
                  type="text"
                  id="website"
                  name="website"
                  value={formData.website}
                  onChange={handleChange}
                  placeholder="Website"
                  className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                />
              </div>
            </div>
          </div>
          <div>
            <h2 className="text-lg font-medium text-gray-900 mb-4">
              Contact Personal Details
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label
                  htmlFor="cFirstName"
                  className="block text-sm font-medium text-gray-700"
                >
                  First Name: <span className="text-red-600">*</span>
                </label>
                <input
                  type="text"
                  id="cFirstName"
                  name="cFirstName"
                  value={formData?.cFirstName}
                  onChange={handleChange}
                  className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="First Name"
                />
              </div>
              <div>
                <label
                  htmlFor="cLastName"
                  className="block text-sm font-medium text-gray-700"
                >
                  Last Name:
                </label>
                <input
                  type="text"
                  id="cLastName"
                  name="cLastName"
                  value={formData?.cLastName}
                  onChange={handleChange}
                  className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="Last Name"
                />
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
              <div>
                <label
                  htmlFor="lEmail"
                  className="block text-sm font-medium text-gray-700"
                >
                  Contact Person Email:
                </label>
                <input
                  placeholder="Contact Person Email"
                  type="email"
                  id="lEmail"
                  name="lEmail"
                  value={formData.lEmail}
                  onChange={handleChange}
                  className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                />
              </div>
              <div>
                <label
                  htmlFor="cPhone"
                  className="block text-sm font-medium text-gray-700"
                >
                  Phone: <span className="text-red-600">*</span>
                </label>
                <input
                  placeholder="Phone"
                  type="tel"
                  id="cPhone"
                  name="cPhone"
                  value={formData.cPhone}
                  onChange={handleChange}
                  className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                />
              </div>
            </div>
          </div>

          {/* Login Details */}
          <div>
            <h2 className="text-lg font-medium text-gray-900 mb-4">
              Login Details
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label
                  htmlFor="cEmail"
                  className="block text-sm font-medium text-gray-700"
                >
                  Email: <span className="text-red-600">*</span>
                </label>
                <input
                  placeholder="Email"
                  type="email"
                  id="cEmail"
                  name="cEmail"
                  value={formData.cEmail}
                  onChange={handleChange}
                  className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                />
              </div>

              {/* Password Field with Toggle */}
              <div className="relative">
                <label
                  htmlFor="password"
                  className="block text-sm font-medium text-gray-700"
                >
                  Password: <span className="text-red-500">*</span>
                </label>
                <div className="relative">
                  <input
                    placeholder="Password"
                    type={showPassword ? "text" : "password"}
                    id="password"
                    name="password"
                    value={formData.password}
                    onChange={handleChange}
                    className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 pr-10 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  />
                  <button
                    type="button"
                    className="absolute inset-y-0 right-0 pr-3 flex items-center mt-1"
                    onClick={() => setShowPassword(!showPassword)}
                  >
                    {showPassword ? (
                      <Eye className="h-4 w-4 text-gray-400" />
                    ) : (
                      <EyeOff className="h-4 w-4 text-gray-400" />
                    )}
                  </button>
                </div>
              </div>

              {/* Confirm Password Field with Toggle */}
              <div className="relative">
                <label
                  htmlFor="cpassword"
                  className="block text-sm font-medium text-gray-700"
                >
                  Confirm Password: <span className="text-red-500">*</span>
                </label>
                <div className="relative">
                  <input
                    placeholder="Confirm Password"
                    type={showConfirmPassword ? "text" : "password"}
                    id="cpassword"
                    name="cpassword"
                    value={formData.cpassword}
                    onChange={handleChange}
                    className={`mt-1 block w-full border rounded-md shadow-sm py-2 px-3 pr-10 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm ${
                      formData.cpassword &&
                      formData.password !== formData.cpassword
                        ? "border-red-500"
                        : formData.password === formData.cpassword
                        ? "border-green-500"
                        : "border-gray-300"
                    }`}
                  />
                  <button
                    type="button"
                    className="absolute inset-y-0 right-0 pr-3 flex items-center mt-1"
                    onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                  >
                    {showConfirmPassword ? (
                      <Eye className="h-4 w-4 text-gray-400" />
                    ) : (
                      <EyeOff className="h-4 w-4 text-gray-400" />
                    )}
                  </button>
                </div>
                {/* Password Match Indicator */}
                {formData.cpassword && (
                  <p
                    className={`text-sm mt-1 ${
                      formData.password === formData.cpassword
                        ? "text-green-600"
                        : "text-red-600"
                    }`}
                  >
                    {formData.password === formData.cpassword
                      ? "✓ Passwords match"
                      : "✗ Passwords Does not match"}
                  </p>
                )}
              </div>
            </div>
          </div>

          {/* Organization Profile */}
          <div>
            <h2 className="text-lg font-medium text-gray-900 mb-4">
              About Info:
            </h2>
            <textarea
              placeholder="About Info"
              id="organisationProfile"
              name="organisationProfile"
              rows={4}
              value={formData.organisationProfile}
              onChange={handleChange}
              className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
            />
          </div>

          {/* Expert the in the following Activities */}
          <div>
            <h2 className="text-lg font-medium text-gray-900 mb-4">
              Expert the in the following Activities:
            </h2>
            <textarea
              placeholder="Expert the in the following Activities"
              id="expert"
              name="expert"
              rows={4}
              value={formData.expert}
              onChange={handleChange}
              className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
            />
          </div>

          {/* References */}
          <div>
            <h2 className="text-lg font-medium text-gray-900 mb-4">
              References
            </h2>
            <p className="text-sm text-gray-600 mb-4">
              You may nominate your professionals for technical Committee for
              IAAB
            </p>

            {/* Add Reference Button */}
            <button
              type="button"
              onClick={addReference}
              className="mb-4 inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700"
            >
              + Add Reference
            </button>

            {references.map((reference, index) => (
              <div
                key={reference._id}
                className="mb-6 p-4 border border-gray-200 rounded-md relative"
              >
                {/* Remove Button */}
                <button
                  type="button"
                  onClick={() => removeReference(index)}
                  className="absolute top-2 right-2 text-red-600 hover:text-red-800 text-lg font-bold"
                >
                  × Remove
                </button>

                <h3 className="text-md font-medium text-gray-900 mb-3">
                  Reference #{index + 1}
                </h3>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700">
                      Full Name:
                    </label>
                    <input
                      placeholder="Full Name"
                      type="text"
                      value={reference.rFullName}
                      onChange={(e) =>
                        handleReferenceChange(
                          index,
                          "rFullName",
                          e.target.value
                        )
                      }
                      className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700">
                      Expertise for
                    </label>
                    <input
                      placeholder="Expertise for"
                      type="text"
                      value={reference.expertiseFor}
                      onChange={(e) =>
                        handleReferenceChange(
                          index,
                          "expertiseFor",
                          e.target.value
                        )
                      }
                      className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                    />
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700">
                      Qualification & work experience
                    </label>
                    <input
                      placeholder="Qualification & work experience"
                      type="text"
                      value={reference.qualificationAndExperience}
                      onChange={(e) =>
                        handleReferenceChange(
                          index,
                          "qualificationAndExperience",
                          e.target.value
                        )
                      }
                      className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700">
                      Phone:
                    </label>
                    <input
                      placeholder="Phone"
                      type="tel"
                      value={reference.rPhone}
                      maxLength={12}
                      minLength={10}
                      onChange={(e) =>
                        handleReferenceChange(index, "rPhone", e.target.value)
                      }
                      className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                    />
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700">
                      Address:
                    </label>
                    <input
                      placeholder="Address"
                      type="text"
                      value={reference.rAddress}
                      onChange={(e) =>
                        handleReferenceChange(index, "rAddress", e.target.value)
                      }
                      className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700">
                      Email:
                    </label>
                    <input
                      placeholder="Email"
                      type="email"
                      value={reference.rEmail}
                      onChange={(e) =>
                        handleReferenceChange(index, "rEmail", e.target.value)
                      }
                      className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                    />
                  </div>
                </div>
              </div>
            ))}
          </div>

          {/* Disclaimer and signature */}
          <div>
            <h2 className="text-lg font-medium text-gray-900 mb-4">
              Disclaimer and signature
            </h2>
            <p className="text-sm text-gray-600 mb-4">
              I/We certify that my/our answers are true and complete to the best
              of my knowledge.
            </p>
            <p className="text-sm text-gray-600 mb-4">
              If this application compliance the requirements of IAAB Members
              norms, I understand that false or misleading information in my/our
              application may lead to disqualify for membership.
            </p>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
              <div>
                <label
                  htmlFor="signature"
                  className="block text-sm font-medium text-gray-700"
                >
                  Signature: <span className="text-red-600">*</span>
                </label>
                <input
                  type="file"
                  name="signature"
                  id="signature"
                  accept="image/*"
                  ref={signatureInputRef}
                  className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  onChange={(e) => {
                    if (e.target.files && e.target.files[0]) {
                      setFormData({
                        ...formData,
                        signature: e.target.files[0] || null,
                      });
                    }
                  }}
                />
              </div>

              <div>
                <label
                  htmlFor="sDate"
                  className="block text-sm font-medium text-gray-700"
                >
                  Date: <span className="text-red-600">*</span>
                </label>
                <input
                  type="date"
                  onKeyDown={(e) => e.preventDefault()}
                  id="sDate"
                  name="sDate"
                  value={formData.sDate}
                  onChange={handleChange}
                  className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                />
              </div>
            </div>
          </div>

          <div className="flex flex-col gap-6 md:flex-row">
            <div className="flex gap-2">
              <label
                htmlFor="captcha"
                className="block text-sm font-medium text-gray-700 mb-1"
              >
                Captcha<span className="text-red-600">*</span>
              </label>
              <input
                id="captcha"
                className="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="Enter Captcha"
                value={formData.captcha}
                onChange={(e) =>
                  setFormData({ ...formData, captcha: e.target.value })
                }
              />
            </div>

            <div className="flex items-center justify-center space-x-2">
              <SafeHtmlRenderer htmlContent={captchaSvg} />
              <button
                type="button"
                onClick={fetchCaptcha}
                className="p-2 rounded-full hover:bg-gray-200"
                aria-label="Regenerate Captcha"
              >
                <RefreshCw className="w-5 h-5" />
              </button>
            </div>
          </div>

          <div className="flex justify-end">
            <button
              type="submit"
              disabled={isSubmitting}
              className={`inline-flex hover:bg-btnhover hover:scale-105 w-36 items-center justify-center px-6 py-2 border border-transparent text-sm font-medium rounded-full text-black bg-btn ${
                isSubmitting ? "opacity-50 cursor-not-allowed" : ""
              }`}
            >
              {isSubmitting ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  Submitting...
                </>
              ) : (
                "Submit"
              )}
            </button>
          </div>
        </form>
        <ToastContainer />
      </div>
    </div>
  );
}
