"use client";
import Image from "next/image";
import { useState, useEffect } from "react";
import { usePathname, useSearchParams, useRouter } from "next/navigation";
import { QRCodeCanvas } from "qrcode.react";
import SafeHtmlRenderer from "../SafeHtmlRenderer";
import {
  RefreshCw,
  User,
  Mail,
  Phone,
  Building2,
  MessageSquare,
  Target,
  CheckCircle,
  XCircle,
  ExternalLink,
} from "lucide-react";
import useAxios from "@/hooks/useAxios";
import axios from "axios";
import { BASE_URL } from "@/Constant";
import Loading from "@/app/loading";
import { toast, ToastContainer } from "react-toastify";
import Loader from "../../components/Loader/Loader";

export default function InnerAbout({ slug }: any) {
  const [formData, setFormData] = useState({
    accreditationId: "",
    name: "",
    contactNo: "",
    emailId: "",
    companyName: "",
    subject: "",
    enquiry: "",
    captcha: "",
    enquiryFrom: "organisation",
  });

  const [accreditation, setAccreditation] = useState<any>(null);
  const [captchaSvg, setCaptchaSvg] = useState("");
  const [loading, setLoading] = useState(false);
  const [currentUrl, setCurrentUrl] = useState("");
  const [accreditationID, setAccreditationID] = useState<any>(null);
  const [accreditationID2, setAccreditationID2] = useState<any>(null);

  const [countries, setCountries] = useState<any[]>([]);
  const [states, setStates] = useState<Record<string, any[]>>({});
  const [cities, setCities] = useState<Record<string, any[]>>({});

  const [notFound, setNotFound] = useState(false);
  const router = useRouter();

  const redirectTo404 = () => {
    setNotFound(true);
    router.push("/404");
  };

  const { postData, getData } = useAxios();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const formatDate = (isoDate: string) => {
    if (!isoDate) return "NA";
    const date = new Date(isoDate);
    return date.toLocaleDateString("en-US", {
      day: "2-digit",
      month: "short",
      year: "numeric",
    });
  };

  const fetchAllCountries = async () => {
    try {
      const res: any = await getData("dropdown/getAllCountry");
      if (res?.success && Array.isArray(res.data)) {
        setCountries(res.data);
      }
    } catch (err) {
      console.error(err);
    }
  };

  const formatUniqueIDForURL = (uniqueID: string) => {
    if (!uniqueID) return ""; // Return empty string if uniqueID is undefined
    return encodeURIComponent(uniqueID.replace(/\//g, "---"));
  };

  const fetchStates = async (countryId: string, key: string) => {
    try {
      const res: any = await getData(
        `dropdown/getAllStates?billcountryid=${countryId}`,
      );
      if (res?.success) {
        setStates((prev) => ({ ...prev, [key]: res.data || [] }));
      }
    } catch (err) {
      console.error(err);
    }
  };

  const fetchCities = async (stateId: string, key: string) => {
    try {
      const res: any = await getData(
        `dropdown/getAllCity?billstateid=${stateId}`,
      );
      if (res?.success) {
        setCities((prev) => ({ ...prev, [key]: res.data || [] }));
      }
    } catch (err) {
      console.error(err);
    }
  };

  // --- Mappers ---
  const getCountryName = (billcountryid: string) => {
    if (!billcountryid) return "-";
    const c = countries.find(
      (c) => String(c.billcountryid) === String(billcountryid),
    );
    return c ? c.billcountry : billcountryid;
  };

  const getStateName = (billstateid: string, index: number) => {
    if (!billstateid) return "-";
    const s = states[`state-${index}`]?.find(
      (st) => String(st.billstateid) === String(billstateid),
    );
    return s ? s.billstate : billstateid;
  };

  const getCityName = (billcityid: string, index: number) => {
    if (!billcityid) return "-";
    const c = cities[`city-${index}`]?.find(
      (ct) => String(ct.billcityid) === String(billcityid),
    );
    return c ? c.billcity : billcityid;
  };

  // Parse standards data
  const parseStandards = () => {
    try {
      if (accreditation?.standards && accreditation.standards.length > 0) {
        if (typeof accreditation.standards[0] === "object") {
          return accreditation.standards;
        }
        if (typeof accreditation.standards[0] === "string") {
          return JSON.parse(accreditation.standards[0]);
        }
      }
      return [];
    } catch (error) {
      console.error("Error parsing standards:", error);
      return [];
    }
  };

  const fetchAccreditationID = async (abName: string) => {
    try {
      console.log("Fetching accreditation for AB ID:", abName);

      const response = await axios.get(
        `${BASE_URL}cb/getCbById?cbId=${abName}`,
      );

      console.log("API Response:", response.data);

      if (response.data?.success && response.data.data) {
        const acc = response.data.data;
        if (acc.abName) {
          console.log("Calling fetchAccreditationID with:", acc.abName);
          fetchAccreditationID2(acc.abName);
        }
        setAccreditationID(acc);
      } else {
        console.log("No accreditation data found");
        setAccreditationID(null);
      }
    } catch (error: any) {
      console.error("Error fetching accreditation ID:", error);
      setAccreditationID(null);
    }
  };

  const fetchAccreditationID2 = async (abName: string) => {
    try {
      console.log("Fetching accreditation for AB ID:", abName);

      const response = await axios.get(
        `${BASE_URL}ab/getAbById?abId=${abName}`,
      );

      console.log("API Response:", response.data);

      if (response.data?.success && response.data.data) {
        const acc = response.data.data;
        setAccreditationID2(acc);
      } else {
        console.log("No accreditation data found");
        setAccreditationID2(null);
      }
    } catch (error: any) {
      console.error("Error fetching accreditation ID:", error);
      setAccreditationID2(null);
    }
  };

  const fetchAccreditation = async () => {
    if (!slug) return;

    try {
      const isUniqueId = /^\d+$/.test(slug);
      const orgEndpoint = isUniqueId
        ? `${BASE_URL}organisation/getOrBySlug?uniqueId=${slug}`
        : `${BASE_URL}organisation/getOrBySlug?slug=${slug}`;

      const orgResponse = await axios.get(orgEndpoint);

      if (orgResponse.data.success && orgResponse.data.data) {
        const orgData = orgResponse.data.data;

        setAccreditation(orgData);
        setFormData((prev) => ({ ...prev, accreditationId: orgData._id }));

        // Fetch Key Locations
        orgData?.KeyLocation?.forEach((loc: any, i: number) => {
          if (loc.country) fetchStates(loc.country, `state-${i}`);
          if (loc.state) fetchCities(loc.state, `city-${i}`);
        });

        if (orgData.accreditationBody) {
          console.log(
            "Calling fetchAccreditationID with:",
            orgData.accreditationBody,
          );
          fetchAccreditationID(orgData.accreditationBody);
        }

        // Fetch CB details
        if (orgData.accreditationBody) {
          const cbData = await fetchCbById(orgData.accreditationBody);
          if (cbData) {
            setAccreditation((prev: any) => ({ ...prev, cbDetails: cbData }));
          }
        }

        return;
      }

      console.warn("No accreditation found for slug:", slug);
      setAccreditation(null);
    } catch (error) {
      console.error("Error fetching accreditation:", error);
      setAccreditation(null);
      redirectTo404();
    }
  };

  const fetchCbById = async (cbId: string) => {
    if (!cbId) return null;

    try {
      const response = await axios.get(`${BASE_URL}cb/getCbById?cbId=${cbId}`);
      if (response.data.success && response.data.data) {
        return response.data.data;
      } else {
        console.warn("CB not found for ID:", cbId);
        return null;
      }
    } catch (error) {
      console.error("Error fetching CB:", error);
      return null;
    }
  };

  const fetchCaptcha = async () => {
    try {
      const { data }: any = await getData("captcha/generateCaptcha", {
        withCredentials: true,
      });
      setCaptchaSvg(data?.captcha);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    fetchAllCountries();
    fetchAccreditation();
    fetchCaptcha();
  }, []);

  useEffect(() => {
    if (typeof window !== "undefined") {
      const params = searchParams?.toString();
      const url = `${window.location.origin}${pathname}${
        params ? `?${params}` : ""
      }`;
      setCurrentUrl(url);
    }
  }, [pathname, searchParams]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // Check required fields
    if (!formData.name) {
      toast.error("Name is required");
      return;
    }
    if (!formData.contactNo) {
      toast.error("Contact number is required");
      return;
    }
    if (!formData.emailId) {
      toast.error("Email is required");
      return;
    }
    if (!formData.companyName) {
      toast.error("Company name is required");
      return;
    }
    if (!formData.subject) {
      toast.error("Subject is required");
      return;
    }
    if (!formData.enquiry) {
      toast.error("Enquiry is required");
      return;
    }
    if (!formData.captcha) {
      toast.error("Captcha is required");
      return;
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(formData.emailId)) {
      toast.error("Please enter a valid email address");
      return;
    }

    setLoading(true);
    try {
      const res: any = await postData("enquiry", formData, {
        withCredentials: true,
      });

      if (res?.success) {
        setFormData({
          accreditationId: accreditation._id,
          name: "",
          contactNo: "",
          emailId: "",
          companyName: "",
          subject: "",
          enquiry: "",
          captcha: "",
          enquiryFrom: "organisation",
        });
        toast.success(res?.message);
      } else {
        toast.error(res?.message);
      }
    } catch (error) {
      console.error(error);
      toast.error("Error submitting form");
    } finally {
      setLoading(false);
      fetchCaptcha();
    }
  };

  if (!accreditation) return <Loading />;

  const standards = parseStandards();

  const hasOrganisationScope =
    accreditation.organisationScope?.trim().length > 0;

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-blue-50 p-4 md:p-8">
      <div className="mx-auto md:w-[87%] bg-white rounded-2xl shadow-xl border border-slate-200 overflow-hidden">
        {/* Header */}
        <div className="bg-gradient-to-r from-blue-600 to-indigo-700 p-6 md:p-5 text-white">
          <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
            <div className="flex items-center gap-6 flex-wrap sm:flex-nowrap">
              {/* Organisation Logo */}
              <div className="w-24 h-24 relative bg-white rounded-lg p-2 shadow-lg">
                {accreditation.glalogo ? (
                  <Image
                    src={`${BASE_URL}${accreditation.glalogo}`}
                    alt={accreditation.organisationName}
                    width={96}
                    height={96}
                    className="w-full h-full object-contain"
                    unoptimized={true}
                  />
                ) : (
                  <div className="w-full h-full bg-slate-100 rounded-lg flex items-center justify-center text-slate-400 text-xs">
                    No Logo
                  </div>
                )}
              </div>

              <div>
                <div>
                  <h4 className="text-xl text-gray-900 font-bold mb-1">
                    {accreditation.organisationName}
                  </h4>
                  {/* <div className="flex items-center">
                    {accreditation.isVerified ? (
                      <>
                        <CheckCircle className="w-4 h-4 text-green-400" />
                        <span className="text-sm text-green-300 ml-1">
                          Verified
                        </span>
                      </>
                    ) : (
                      <>
                        <XCircle className="w-4 h-4 text-red-400" />
                        <span className="text-sm text-red-300 ml-1">
                          Not Verified
                        </span>
                      </>
                    )}
                  </div> */}
                </div>
                <div className="flex items-center mt-2">
                  <span
                    className={`
    px-3 py-1 rounded-full text-sm font-medium
    ${accreditation.certificateStatus === "Active" ? "bg-green-100 text-green-800" : ""}
    ${accreditation.certificateStatus === "Suspend" ? "bg-yellow-100 text-yellow-800" : ""}
    ${accreditation.certificateStatus === "Withdrawn" ? "bg-red-100 text-red-800" : ""}
    ${accreditation.certificateStatus === "Cancelled" ? "bg-gray-100 text-gray-800" : ""}
  `}
                  >
                    {accreditation.certificateStatus}
                  </span>
                </div>
              </div>
            </div>

            <div className="flex flex-row gap-3">
              {currentUrl && (
                <div className="text-center">
                  <QRCodeCanvas
                    value={currentUrl}
                    size={80}
                    level="H"
                    includeMargin
                  />
                  <span className="text-sm text-slate-600 mt-2 block">
                    Scan QR Code
                  </span>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Content */}
        <div className="p-6 md:p-5">
          <div className="p-6 md:p-5">
            <section className="mb-8">
              <h2 className="text-xl font-bold text-slate-800 mb-3">
                Unique Identification Number
              </h2>
              <p className="bg-gray-100 mb-1 p-2 rounded-md text-blue-100 text-lg">
                {accreditation.uniqueId}
              </p>
            </section>

            {/* Organisation Scope Section - Only show if it exists */}
            {hasOrganisationScope && (
              <section className="mb-8">
                <div className="flex items-center gap-3 mb-4">
                  <h2 className="text-xl font-bold text-slate-800 mb-1">
                    Organisation Scope/Activities
                  </h2>
                </div>
                <div className="bg-slate-50 rounded-xl p-3 border border-slate-200">
                  <p
                    className="text-slate-700 leading-relaxed text-base"
                    ref={(el) => {
                      if (el)
                        el.style.setProperty("font-size", "14px", "important");
                    }}
                  >
                    {accreditation.organisationScope}
                  </p>
                </div>
              </section>
            )}

            {/* Standards Section */}
            {standards.length > 0 && (
              <section className="mb-8">
                <h2 className="text-xl font-bold text-slate-800 mb-4">
                  Standards
                </h2>
                <div className="overflow-x-auto bg-slate-50 rounded-xl border border-slate-200">
                  <table className="w-full">
                    <thead className="bg-gray-100">
                      <tr>
                        <th
                          className="px-4 py-3 text-left text-sm font-semibold text-gray-700"
                          ref={(el) => {
                            if (el)
                              el.style.setProperty(
                                "font-size",
                                "14px",
                                "important",
                              );
                          }}
                        >
                          Standard Number
                        </th>
                        <th
                          className="px-4 py-3 text-left text-sm font-semibold text-gray-700"
                          ref={(el) => {
                            if (el)
                              el.style.setProperty(
                                "font-size",
                                "14px",
                                "important",
                              );
                          }}
                        >
                          GLA Approval Status
                        </th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200">
                      {standards.map((standard: any, index: number) => (
                        <tr
                          key={standard._id || index}
                          ref={(el) => {
                            if (el)
                              el.style.setProperty(
                                "font-size",
                                "14px",
                                "important",
                              );
                          }}
                        >
                          <td
                            className="px-4 py-3 text-sm text-gray-700"
                            ref={(el) => {
                              if (el)
                                el.style.setProperty(
                                  "font-size",
                                  "14px",
                                  "important",
                                );
                            }}
                          >
                            {standard.standardNumber || "N/A"}
                          </td>
                          <td
                            className="px-4 py-3 text-sm text-gray-700"
                            ref={(el) => {
                              if (el)
                                el.style.setProperty(
                                  "font-size",
                                  "14px",
                                  "important",
                                );
                            }}
                          >
                            {standard.glaApprovalStatus || "N/A"}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </section>
            )}

            {/* Key Locations */}
            {accreditation.KeyLocation?.length > 0 && (
              <section className="mb-8">
                <h2 className="text-xl font-bold text-slate-800 mb-4">
                  Key Locations
                </h2>
                <div className="overflow-x-auto bg-slate-50 rounded-xl border border-slate-200">
                  <table className="w-full">
                    <thead className="bg-gray-100">
                      <tr>
                        <th
                          className="px-4 py-3 text-left text-sm font-semibold text-gray-700"
                          ref={(el) => {
                            if (el)
                              el.style.setProperty(
                                "font-size",
                                "14px",
                                "important",
                              );
                          }}
                        >
                          Address Type
                        </th>
                        <th
                          className="px-4 py-3 text-left text-sm font-semibold text-gray-700"
                          ref={(el) => {
                            if (el)
                              el.style.setProperty(
                                "font-size",
                                "14px",
                                "important",
                              );
                          }}
                        >
                          Address
                        </th>
                        <th
                          className="px-4 py-3 text-left text-sm font-semibold text-gray-700"
                          ref={(el) => {
                            if (el)
                              el.style.setProperty(
                                "font-size",
                                "14px",
                                "important",
                              );
                          }}
                        >
                          Country
                        </th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200">
                      {accreditation.KeyLocation?.map(
                        (loc: any, idx: number) => (
                          <tr
                            key={idx}
                            ref={(el) => {
                              if (el)
                                el.style.setProperty(
                                  "font-size",
                                  "14px",
                                  "important",
                                );
                            }}
                          >
                            <td
                              className="px-4 py-3 text-sm text-gray-700 capitalize"
                              ref={(el) => {
                                if (el)
                                  el.style.setProperty(
                                    "font-size",
                                    "14px",
                                    "important",
                                  );
                              }}
                            >
                              {loc.registeredAddress?.replace(/_/g, " ") ||
                                "N/A"}
                            </td>
                            <td
                              className="px-4 py-3 text-sm text-gray-700"
                              ref={(el) => {
                                if (el)
                                  el.style.setProperty(
                                    "font-size",
                                    "14px",
                                    "important",
                                  );
                              }}
                            >
                              {loc.address || "N/A"}
                            </td>
                            <td
                              className="px-4 py-3 text-sm text-gray-700"
                              ref={(el) => {
                                if (el)
                                  el.style.setProperty(
                                    "font-size",
                                    "14px",
                                    "important",
                                  );
                              }}
                            >
                              {getCountryName(loc.country) || "Loading..."}
                            </td>
                          </tr>
                        ),
                      )}
                    </tbody>
                  </table>
                </div>
              </section>
            )}

            <section className="mb-8">
              <h2 className="text-xl font-bold text-slate-800 mb-4">
                Certificate Information
              </h2>
              <div className="overflow-x-auto bg-slate-50 rounded-xl border border-slate-200">
                <table className="w-full">
                  <tbody className="divide-y divide-gray-200 text-sm">
                    <tr>
                      <td
                        className="px-4 py-3 font-semibold text-gray-700"
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        Certificate Original Issued Date
                      </td>
                      <td
                        className="px-4 py-3 text-gray-600"
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        {formatDate(
                          accreditation.certificateOriginalIssuedDate,
                        )}
                      </td>
                    </tr>

                    <tr>
                      <td
                        className="px-4 py-3 font-semibold text-gray-700"
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        Certificate Current Issued Date
                      </td>
                      <td
                        className="px-4 py-3 text-gray-600"
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        {formatDate(accreditation.certificateCurrentIssuedDate)}
                      </td>
                    </tr>

                    <tr>
                      <td
                        className="px-4 py-3 font-semibold text-gray-700"
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        Certificate Expiry Date
                      </td>
                      <td
                        className="px-4 py-3 text-gray-600"
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        {formatDate(accreditation.certificateExpiryDate)}
                      </td>
                    </tr>

                    <tr>
                      <td
                        className="px-4 py-3 font-semibold text-gray-700"
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        Certification Type
                      </td>
                      <td
                        className="px-4 py-3 text-gray-600"
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        {accreditation.certificationType || "NA"}
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </section>

            {/* Accreditation & Certification Bodies Section */}
            <section className="mb-7 mt-9">
              <h2 className="text-xl font-bold text-slate-800 mb-4">
                Certification & Accreditation Bodies
              </h2>
              <div className="overflow-x-auto bg-slate-50 rounded-xl border border-slate-200">
                <table className="w-full">
                  <thead className="bg-gray-100">
                    <tr>
                      <th
                        className="px-4 py-3 text-left text-sm font-semibold text-gray-700"
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        Organisation Name
                      </th>
                      <th
                        className="px-4 py-3 text-left text-sm font-semibold text-gray-700"
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        Link
                      </th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200">
                    {/* Render Certification Body only if accreditationID exists */}
                    {accreditationID && (
                      <tr>
                        <td
                          className="px-4 py-3 text-sm text-gray-700 capitalize"
                          ref={(el) => {
                            if (el)
                              el.style.setProperty(
                                "font-size",
                                "14px",
                                "important",
                              );
                          }}
                        >
                          {accreditationID.organisationName || "N/A"}{" "}
                          (Certification Body)
                        </td>
                        <td
                          className="px-4 py-3 text-sm text-gray-700"
                          ref={(el) => {
                            if (el)
                              el.style.setProperty(
                                "font-size",
                                "14px",
                                "important",
                              );
                          }}
                        >
                          <a
                            href={`/certificationbody/${formatUniqueIDForURL(
                              accreditationID.slug,
                            )}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="inline-flex items-center bg-btn-ob gap-1 px-3 py-1.5 bg-blue-50 text-black hover:bg-blue-100 border border-blue-200 rounded-lg transition-colors text-sm font-medium"
                          >
                            View Details
                            <ExternalLink className="w-3 h-3" />
                          </a>
                        </td>
                      </tr>
                    )}

                    {/* Render Accreditation Body only if accreditationID2 exists */}
                    {accreditationID2 && (
                      <tr>
                        <td
                          className="px-4 py-3 text-sm text-gray-700 capitalize"
                          ref={(el) => {
                            if (el)
                              el.style.setProperty(
                                "font-size",
                                "14px",
                                "important",
                              );
                          }}
                        >
                          {accreditationID2.organisationName || "N/A"}{" "}
                          (Accreditation Body)
                        </td>
                        <td
                          className="px-4 py-3 text-sm text-gray-700"
                          ref={(el) => {
                            if (el)
                              el.style.setProperty(
                                "font-size",
                                "14px",
                                "important",
                              );
                          }}
                        >
                          <a
                            href={`/accreditationbody/${formatUniqueIDForURL(
                              accreditationID2.slug,
                            )}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="inline-flex items-center bg-btn-ob gap-1 px-3 py-1.5 bg-blue-50 text-black hover:bg-blue-100 border border-blue-200 rounded-lg transition-colors text-sm font-medium"
                          >
                            View Details
                            <ExternalLink className="w-3 h-3" />
                          </a>
                        </td>
                      </tr>
                    )}

                    {/* Show message if no accreditation bodies found */}
                    {!accreditationID && !accreditationID2 && (
                      <tr>
                        <td
                          colSpan={2}
                          className="px-4 py-3 text-sm text-gray-500 text-center"
                        >
                          No accreditation bodies information available
                        </td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            </section>

            {/* Enquiry Form */}
            <div
              className="bg-gradient-to-r from-slate-50 to-blue-50 rounded-2xl p-6 border border-slate-200 mt-16"
              style={{ backgroundColor: "beige" }}
            >
              <h2 className="text-xl font-bold text-slate-800 mb-6">
                Get In Touch
              </h2>
              <form onSubmit={handleSubmit} className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label
                      htmlFor="name"
                      className="flex items-center gap-2 text-sm font-medium text-slate-700 mb-2"
                    >
                      <User className="w-4 h-4 text-blue-600" />
                      Name <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      id="name"
                      placeholder="Enter your full name"
                      className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm bg-white"
                      value={formData.name}
                      onChange={(e) =>
                        setFormData({ ...formData, name: e.target.value })
                      }
                      required
                    />
                  </div>
                  <div>
                    <label
                      htmlFor="emailId"
                      className="flex items-center gap-2 text-sm font-medium text-slate-700 mb-2"
                    >
                      <Mail className="w-4 h-4 text-blue-600" />
                      Email <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="email"
                      id="emailId"
                      placeholder="Enter email address"
                      className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm bg-white"
                      value={formData.emailId}
                      onChange={(e) =>
                        setFormData({ ...formData, emailId: e.target.value })
                      }
                      required
                    />
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label
                      htmlFor="contactNo"
                      className="flex items-center gap-2 text-sm font-medium text-slate-700 mb-2"
                    >
                      <Phone className="w-4 h-4 text-blue-600" />
                      Phone <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      id="contactNo"
                      placeholder="Enter contact number"
                      className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm bg-white"
                      value={formData.contactNo}
                      onChange={(e) =>
                        setFormData({ ...formData, contactNo: e.target.value })
                      }
                      required
                    />
                  </div>

                  <div>
                    <label
                      htmlFor="companyName"
                      className="flex items-center gap-2 text-sm font-medium text-slate-700 mb-2"
                    >
                      <Building2 className="w-4 h-4 text-blue-600" />
                      Company <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      id="companyName"
                      placeholder="Enter company name"
                      className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm bg-white"
                      value={formData.companyName}
                      onChange={(e) =>
                        setFormData({
                          ...formData,
                          companyName: e.target.value,
                        })
                      }
                      required
                    />
                  </div>
                </div>

                <div>
                  <label
                    htmlFor="subject"
                    className="block text-sm font-medium text-slate-700 mb-2"
                  >
                    Subject <span className="text-red-500">*</span>
                  </label>
                  <select
                    id="subject"
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm bg-white"
                    value={formData.subject}
                    onChange={(e) =>
                      setFormData({ ...formData, subject: e.target.value })
                    }
                    required
                  >
                    <option value="">Select Subject</option>
                    <option value="General">General Enquiry</option>
                    <option value="Support">Support</option>
                    <option value="Feedback">Feedback</option>
                    <option value="Appeal">Appeal</option>
                    <option value="Complaint">Complaint</option>
                  </select>
                </div>

                <div>
                  <label
                    htmlFor="enquiry"
                    className="flex items-center gap-2 text-sm font-medium text-slate-700 mb-2"
                  >
                    <MessageSquare className="w-4 h-4 text-blue-600" />
                    Enquiry Details <span className="text-red-500">*</span>
                  </label>
                  <textarea
                    id="enquiry"
                    placeholder="Write your enquiry here..."
                    rows={4}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm bg-white resize-none"
                    value={formData.enquiry}
                    onChange={(e) =>
                      setFormData({ ...formData, enquiry: e.target.value })
                    }
                    required
                  />
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-6 items-center">
                  <div>
                    <label
                      htmlFor="captcha"
                      className="block text-sm font-medium text-slate-700 mb-2"
                    >
                      Captcha <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      id="captcha"
                      placeholder="Enter captcha"
                      className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm bg-white"
                      value={formData.captcha}
                      onChange={(e) =>
                        setFormData({ ...formData, captcha: e.target.value })
                      }
                      required
                    />
                  </div>

                  <div className="flex items-center gap-3 mt-2">
                    <SafeHtmlRenderer htmlContent={captchaSvg} />
                    <button
                      type="button"
                      onClick={fetchCaptcha}
                      className="p-3 rounded-lg hover:bg-slate-100 transition border border-slate-200"
                      aria-label="Regenerate Captcha"
                    >
                      <RefreshCw className="w-4 h-4 text-slate-600" />
                    </button>
                  </div>
                </div>

                {loading ? (
                  <div className="flex justify-center">
                    <Loader />
                  </div>
                ) : (
                  <button
                    type="submit"
                    className="px-6 py-2 bg-iaab-gradient rounded-xl border border-gray-300 hover:border-gray-400 shadow-sm disabled:opacity-60"
                  >
                    Send Message
                  </button>
                )}
              </form>

              <ToastContainer />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
