"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 = {
  email: "Email",
  firstName: "First Name",
  phone: "Phone Number",
  sDate: "Signature Date",
  signature: "Signature upload",
  profilelogo: "Profile Logo upload",
  password: "Password",
  cpassword: "Confirm Password",
  expertise: "Your Expertise In Which Sector",
};

function checkErrorBeforSend(data: any) {
  const {
    email,
    firstName,
    phone,
    sDate,
    signature,
    profilelogo,
    password,
    cpassword,
  } = data;

  const requiredFields = {
    email,
    firstName,
    phone,
    sDate,
    signature,
    profilelogo,
    password,
    cpassword,
  };

  const missingFields = Object.entries(requiredFields)
    .filter(
      ([key, value]) => value === undefined || value === null || value === ""
    )
    .map(([key]) => mendatoryField[key]);

  return missingFields;
}

export default function ProfessionalForm() {
  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[]>([]);

  // Single work experience object
  const [workExperience, setWorkExperience] = useState({
    company: "",
    website: "",
    address: "",
    country: "",
    jobTitle: "",
    startDate: "",
    endDate: "",
    responsibilities: "",
    jobDocument: null as File | null,
  });

  const signatureInputRef = useRef<HTMLInputElement | null>(null);
  const profileLogoInputRef = useRef<HTMLInputElement | null>(null);
  const expertiseFileInputRef = useRef<HTMLInputElement | null>(null);
  const assessmentLogsFileInputRef = useRef<HTMLInputElement | null>(null);
  const jobDocumentInputRef = useRef<HTMLInputElement | null>(null);

  const [formData, setFormData] = useState({
    // Personal details
    password: "",
    cpassword: "",
    firstName: "",
    lastName: "",
    date: "",
    streetAddress: "",
    aptUnit: "",
    country: "",
    city: "",
    state: "",
    zipcode: "",
    citizenship: "",
    gender: "",
    phone: "",
    email: "",

    // Professional details
    expertise: "",
    expertiseFile: null as File | null,
    assessmentLogs: "",
    assessmentLogsFile: null as File | null,

    // Files
    signature: null as File | null,
    profilelogo: null as File | null,
    sDate: "",
    captcha: "",
  });

  // 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 | HTMLSelectElement
    >
  ) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleWorkExperienceChange = (
    field: string,
    value: string | File | null
  ) => {
    setWorkExperience((prev) => ({
      ...prev,
      [field]: 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.country) {
      fetchAllStates(formData.country);
    }
  }, [formData.country]);

  useEffect(() => {
    if (formData.state) {
      fetchAllCities(formData.state);
    }
  }, [formData.state]);

  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() !== ""
      )
    );

    // Loading state start
    setIsSubmitting(true);

    try {
      // Step 1: Password validation
      if (formData.password !== formData.cpassword) {
        toast.error("🔐 Password and Confirm Password Does not match!");
        setIsSubmitting(false);
        return;
      }

      // Step 2: Password strength check
      if (formData.password.length < 6) {
        toast.error("🔒 Password must be at least 6 characters long!");
        setIsSubmitting(false);
        return;
      }

      // Step 3: Validate required fields
      const missingFields = checkErrorBeforSend(formData);

      if (missingFields.length > 0) {
        toast.error(`Required Fields are: ${missingFields.join(", ")}`);
        setIsSubmitting(false);
        return;
      }

      // Step 4: Prepare form data
      const formDataToSend = new FormData();

      // Append form data
      for (const key in formData) {
        const value = formData[key as keyof typeof formData];
        if (
          (key === "signature" ||
            key === "profilelogo" ||
            key === "expertiseFile" ||
            key === "assessmentLogsFile") &&
          value
        ) {
          formDataToSend.append(key, value);
        } else {
          formDataToSend.append(key, String(value || ""));
        }
      }

      formDataToSend.append("workExperiencecompany", workExperience.company);
      formDataToSend.append("workExperiencewebsite", workExperience.website);
      formDataToSend.append("workExperienceaddress", workExperience.address);
      formDataToSend.append("workExperiencecountry", workExperience.country);
      formDataToSend.append("workExperiencejobTitle", workExperience.jobTitle);
      formDataToSend.append(
        "workExperienceresponsibilities",
        workExperience.responsibilities
      );

      if (workExperience.jobDocument) {
        formDataToSend.append(
          "workExperiencejobDocument",
          workExperience.jobDocument
        );
        console.log("Job Document appended to FormData");
      } else {
        console.log(" No Job Document found");
      }

      formDataToSend.append("references", JSON.stringify(filteredReferences));

      console.log("📤 Sending FormData:");
      for (let [key, value] of formDataToSend.entries()) {
        console.log(`🔑 ${key}:`, value);
      }

      // Show loading toast
      const loadingToast = toast.loading(
        "Submitting your professional membership application..."
      );

      const response = await axios.post(
        `${BASE_URL}professional-member/withoutLogin`,
        formDataToSend,
        {
          headers: {
            "Content-Type": "multipart/form-data",
          },
          withCredentials: true,
          timeout: 30000, // 30 seconds timeout
        }
      );

      // Dismiss loading toast
      toast.dismiss(loadingToast);

      if (response.data.success) {
        toast.success(
          response.data.message ||
            "Professional membership application submitted successfully!"
        );

        // Reset form data
        setFormData({
          password: "",
          cpassword: "",
          firstName: "",
          lastName: "",
          date: "",
          streetAddress: "",
          aptUnit: "",
          country: "",
          city: "",
          state: "",
          zipcode: "",
          citizenship: "",
          gender: "",
          phone: "",
          email: "",
          expertise: "",
          expertiseFile: null,
          assessmentLogs: "",
          assessmentLogsFile: null,
          signature: null,
          profilelogo: null,
          sDate: "",
          captcha: "",
        });

        // Reset work experience
        setWorkExperience({
          company: "",
          website: "",
          address: "",
          country: "",
          jobTitle: "",
          startDate: "",
          endDate: "",
          responsibilities: "",
          jobDocument: null,
        });

        // Reset references
        setReferences([]);

        // Clear file inputs
        [
          signatureInputRef,
          profileLogoInputRef,
          expertiseFileInputRef,
          assessmentLogsFileInputRef,
          jobDocumentInputRef,
        ].forEach((ref) => {
          if (ref.current) ref.current.value = "";
        });

        // Reload captcha
        fetchCaptcha();
      } else {
        toast.warning(
          response.data.message || "Something went wrong! Please try again."
        );
      }
    } catch (error: any) {
      console.error("Submission Error:", error);

      // Dismiss any loading toasts if present
      toast.dismiss();

      if (error.code === "ECONNABORTED") {
        toast.error(
          "⏰ Request timeout! Please check your internet connection and try again."
        );
      } else if (error.response?.status >= 500) {
        toast.error("🔧 Server error! Please try again later.");
      } else {
        toast.error(
          error?.response?.data?.message ||
            "An error occurred during submission. Please try again."
        );
      }

      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">
            APPLY MEMBERSHIP SCHEME FOR PROFESSIONAL MEMBERS
          </p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-8">
          {/* Application Information */}
          <div>
            <h2 className="text-lg font-medium text-gray-900 mb-4">
              Application Information
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label
                  htmlFor="firstName"
                  className="block text-sm font-medium text-gray-700"
                >
                  First Name<span className="text-red-500">*</span>
                </label>
                <input
                  placeholder="First Name"
                  type="text"
                  id="firstName"
                  name="firstName"
                  value={formData.firstName}
                  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="lastName"
                  className="block text-sm font-medium text-gray-700"
                >
                  Last Name
                </label>
                <input
                  placeholder="Last Name"
                  type="text"
                  id="lastName"
                  name="lastName"
                  value={formData.lastName}
                  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>

              {/* Profile Logo Upload */}
              <div>
                <label
                  htmlFor="profilelogo"
                  className="block text-sm font-medium text-gray-700"
                >
                  Profile Logo: <span className="text-red-500">*</span>
                </label>
                <input
                  placeholder="Profile Logo"
                  type="file"
                  name="profilelogo"
                  id="profilelogo"
                  accept="image/*"
                  ref={profileLogoInputRef}
                  className="mt-1 block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
                  onChange={(e) => {
                    setFormData({
                      ...formData,
                      profilelogo: e.target.files ? e.target.files[0] : null,
                    });
                  }}
                />
                <p className="text-xs text-gray-500 mt-1">
                  Upload your profile logo (PNG, JPG, JPEG)
                </p>
              </div>

              <div>
                <label
                  htmlFor="date"
                  className="block text-sm font-medium text-gray-700"
                >
                  DOB
                </label>
                <input
                  placeholder="DOB"
                  type="date"
                  onKeyDown={(e) => e.preventDefault()}
                  id="date"
                  name="date"
                  value={formData.date}
                  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="streetAddress"
                  className="block text-sm font-medium text-gray-700"
                >
                  Street Address
                </label>
                <input
                  placeholder="Street Address"
                  type="text"
                  id="streetAddress"
                  name="streetAddress"
                  value={formData.streetAddress}
                  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="aptUnit"
                  className="block text-sm font-medium text-gray-700"
                >
                  Apt/Unit
                </label>
                <input
                  placeholder="Apt/Unit"
                  type="text"
                  id="aptUnit"
                  name="aptUnit"
                  value={formData.aptUnit}
                  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="country"
                  className="block text-sm font-medium text-gray-700"
                >
                  Country
                </label>
                <select
                  id="country"
                  name="country"
                  value={formData.country}
                  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"
                >
                  <option value="">Select Country</option>
                  {countryDropdown.map((country: any) => (
                    <option
                      key={country.billcountryid}
                      value={country.billcountryid}
                    >
                      {country.billcountry}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label
                  htmlFor="state"
                  className="block text-sm font-medium text-gray-700"
                >
                  State
                </label>
                <select
                  id="state"
                  name="state"
                  value={formData.state}
                  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"
                >
                  <option value="">Select State</option>
                  {stateDropdown.map((state: any) => (
                    <option key={state.billstateid} value={state.billstateid}>
                      {state.billstate}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label
                  htmlFor="city"
                  className="block text-sm font-medium text-gray-700"
                >
                  City
                </label>
                <select
                  id="city"
                  name="city"
                  value={formData.city}
                  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"
                >
                  <option value="">Select city</option>
                  {cityDropdown.map((city: any) => (
                    <option key={city.billcityid} value={city.billcityid}>
                      {city.billcity}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label
                  htmlFor="zipcode"
                  className="block text-sm font-medium text-gray-700"
                >
                  Zip Code
                </label>
                <input
                  placeholder="Zip Code"
                  type="text"
                  id="zipcode"
                  name="zipcode"
                  value={formData.zipcode}
                  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="citizenship"
                  className="block text-sm font-medium text-gray-700"
                >
                  Are you a citizen of which country?
                </label>
                <input
                  placeholder="Are you a citizen of which country?"
                  type="text"
                  id="citizenship"
                  name="citizenship"
                  value={formData.citizenship}
                  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="gender"
                  className="block text-sm font-medium text-gray-700"
                >
                  Gender
                </label>
                <select
                  id="gender"
                  name="gender"
                  value={formData.gender}
                  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"
                >
                  <option value="">Select gender</option>
                  <option value="male">Male</option>
                  <option value="female">Female</option>
                  <option value="other">Other</option>
                </select>
              </div>

              <div>
                <label
                  htmlFor={"phone"}
                  className="block text-sm font-medium text-gray-700"
                >
                  Phone:<span className="text-red-500">*</span>
                </label>
                <input
                  placeholder="Phone"
                  type="tel"
                  name="phone"
                  id={"phone"}
                  value={formData.phone}
                  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>

            {/* Professional Details */}
            <div className="grid grid-cols-1 mt-6">
              <div>
                <label
                  htmlFor="expertise"
                  className="block text-sm font-medium text-gray-700"
                >
                  Your Expertise in which sector
                  <span className="text-red-500">*</span>
                </label>
                <textarea
                  placeholder="Your Expertise in which sector"
                  id="expertise"
                  name="expertise"
                  value={formData.expertise}
                  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 className="mt-4">
                <label
                  htmlFor="expertiseFile"
                  className="block text-sm font-medium text-gray-700"
                >
                  Upload document evidence (Expertise)
                </label>
                <input
                  placeholder="Upload document evidence (Expertise)"
                  type="file"
                  name="expertiseFile"
                  id="expertiseFile"
                  accept=".pdf,.doc,.docx"
                  ref={expertiseFileInputRef}
                  className="mt-1 block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
                  onChange={(e) => {
                    const file = e.target.files?.[0] || null;
                    console.log("📁 Selected expertise file:", file);
                    setFormData({
                      ...formData,
                      expertiseFile: file,
                    });
                  }}
                />
                <p className="text-xs text-gray-500 mt-1">
                  Upload PDF or Document files only
                </p>
              </div>

              <div className="mt-4">
                <label
                  htmlFor="assessmentLogs"
                  className="block text-sm font-medium text-gray-700"
                >
                  Assessment logs / Audit logs / consultancy logs or any
                  professional work experience
                </label>
                <textarea
                  placeholder="Assessment logs / Audit logs / consultancy logs or any
                  professional work experience"
                  id="assessmentLogs"
                  name="assessmentLogs"
                  value={formData.assessmentLogs}
                  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 className="mt-4">
                <label
                  htmlFor="assessmentLogsFile"
                  className="block text-sm font-medium text-gray-700"
                >
                  Upload document evidence (Assessment Logs)
                </label>
                <input
                  placeholder="Upload document evidence (Assessment Logs)"
                  type="file"
                  name="assessmentLogsFile"
                  id="assessmentLogsFile"
                  accept=".pdf,.doc,.docx"
                  ref={assessmentLogsFileInputRef}
                  className="mt-1 block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
                  onChange={(e) => {
                    const file = e.target.files?.[0] || null;
                    console.log("📁 Selected assessment logs file:", file);
                    setFormData({
                      ...formData,
                      assessmentLogsFile: file,
                    });
                  }}
                />
                <p className="text-xs text-gray-500 mt-1">
                  Upload PDF or Document files only
                </p>
              </div>
            </div>
          </div>
          <h2 className="text-lg font-medium text-gray-900 mb-4">
            Login Details
          </h2>
          {/* Login Details */}
          <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label
                htmlFor="email"
                className="block text-sm font-medium text-gray-700"
              >
                Email:<span className="text-red-500">*</span>
              </label>
              <input
                placeholder="Email"
                type="email"
                id="email"
                name="email"
                value={formData.email}
                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>
          {/* Work Experience - Single Section */}
          <div>
            <h2 className="text-lg font-medium text-gray-900 mb-4">
              Work Experience
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6 border p-4 rounded-md">
              <div>
                <label className="block text-sm font-medium text-gray-700">
                  Company
                </label>
                <input
                  placeholder="Company"
                  type="text"
                  value={workExperience.company}
                  onChange={(e) =>
                    handleWorkExperienceChange("company", e.target.value)
                  }
                  className="mt-1 block w-full border border-gray-300 rounded-md py-2 px-3"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700">
                  Website
                </label>
                <input
                  placeholder="Website"
                  type="text"
                  value={workExperience.website}
                  onChange={(e) =>
                    handleWorkExperienceChange("website", e.target.value)
                  }
                  className="mt-1 block w-full border border-gray-300 rounded-md py-2 px-3"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700">
                  Address
                </label>
                <input
                  placeholder="Address"
                  type="text"
                  value={workExperience.address}
                  onChange={(e) =>
                    handleWorkExperienceChange("address", e.target.value)
                  }
                  className="mt-1 block w-full border border-gray-300 rounded-md py-2 px-3"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700">
                  Country
                </label>
                <input
                  placeholder="Country"
                  type="text"
                  value={workExperience.country}
                  onChange={(e) =>
                    handleWorkExperienceChange("country", e.target.value)
                  }
                  className="mt-1 block w-full border border-gray-300 rounded-md py-2 px-3"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700">
                  Job Title
                </label>
                <input
                  placeholder="Job Title"
                  type="text"
                  value={workExperience.jobTitle}
                  onChange={(e) =>
                    handleWorkExperienceChange("jobTitle", e.target.value)
                  }
                  className="mt-1 block w-full border border-gray-300 rounded-md py-2 px-3"
                />
              </div>
              <div className="md:col-span-2">
                <label className="block text-sm font-medium text-gray-700">
                  Responsibilities
                </label>
                <textarea
                  placeholder="Responsibilities"
                  value={workExperience.responsibilities}
                  onChange={(e) =>
                    handleWorkExperienceChange(
                      "responsibilities",
                      e.target.value
                    )
                  }
                  className="mt-1 block w-full border border-gray-300 rounded-md py-2 px-3"
                />
              </div>
              <div className="md:col-span-2">
                <label className="block text-sm font-medium text-gray-700">
                  Upload Job Document
                </label>
                <input
                  placeholder="Upload Job Document"
                  type="file"
                  accept=".pdf,.doc,.docx"
                  ref={jobDocumentInputRef}
                  onChange={(e) =>
                    handleWorkExperienceChange(
                      "jobDocument",
                      e.target.files?.[0] || null
                    )
                  }
                  className="mt-1 block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
                />
                <p className="text-xs text-gray-500 mt-1">
                  Upload PDF or Document files only
                </p>
              </div>
            </div>
          </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-500">*</span>
                </label>
                <input
                  placeholder="Signature"
                  type="file"
                  name="signature"
                  id="signature"
                  accept="image/*"
                  ref={signatureInputRef}
                  className="mt-1 block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
                  onChange={(e) => {
                    setFormData({
                      ...formData,
                      signature: e.target.files ? e.target.files[0] : null,
                    });
                  }}
                />
              </div>

              <div>
                <label
                  htmlFor="sDate"
                  className="block text-sm font-medium text-gray-700"
                >
                  Date:<span className="text-red-500">*</span>
                </label>
                <input
                  placeholder="Date"
                  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>

          {/* Captcha */}
          <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 transition-all duration-200 ${
                isSubmitting
                  ? "opacity-50 cursor-not-allowed transform scale-95"
                  : "hover:scale-105"
              }`}
            >
              {isSubmitting ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  Submitting...
                </>
              ) : (
                "Submit"
              )}
            </button>
          </div>
        </form>
        <ToastContainer
          position="top-right"
          autoClose={5000}
          hideProgressBar={false}
          newestOnTop={false}
          closeOnClick
          rtl={false}
          pauseOnFocusLoss
          draggable
          pauseOnHover
          theme="light"
        />
      </div>
    </div>
  );
}
