"use client";
import element1 from "@/assets/auth/auth-element-1.png";
import element2 from "@/assets/auth/auth-element-2.svg";
import element3 from "@/assets/auth/auth-element-3.svg";
import authImage from "@/assets/auth/auth-image.png";
import line from "@/assets/auth/auth-line.svg";
import LanguageDropdown from "@/components/dashboard/UserDropdown/LanguageDropdown";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useSettings } from "@/context/settingsContext";
import { useT } from "@/context/TranslationContext";
import ApiPath from "@/network/api/apiPath";
import NetworkService from "@/network/service/networkService";
import TokenService from "@/network/service/tokenService";
import { decrypt } from "@/utils/crypto";
import { getSettingValue } from "@/utils/utils";
import Image from "next/image";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "react-toastify";

const IdVerificationChoose = () => {
  const network = new NetworkService();
  const tokenService = new TokenService();
  const router = useRouter();
  const [documentType, setDocumentType] = useState("");
  const [documentTypeLoading, setDocumentTypeLoading] = useState(false);
  const [documentTypes, setDocumentTypes] = useState([]);
  const searchParams = useSearchParams();
  const encryptedToken = searchParams.get("token");
  const token = encryptedToken ? decrypt(encryptedToken) : null;
  const landingUrl = process.env.NEXT_PUBLIC_LANDING_PAGE || "/";
  const { settings } = useSettings();
  const siteLogo = getSettingValue(settings, "site_logo");
  const siteLogoHeight = getSettingValue(settings, "site_logo_height");
  const t = useT();

  const handleToken = async () => {
    if (!token) return;
    try {
      await tokenService.saveAccessToken(token);
    } catch (error) {
      console.error(error);
    }
  };

  // Fetch document types
  const fetchDocumentTypes = async () => {
    try {
      setDocumentTypeLoading(true);
      const res = await network.get(ApiPath.documentTypes, {
        for: "agent",
      });
      if (res.status === "completed") {
        setDocumentTypes(res.data.data);
      }
    } finally {
      setDocumentTypeLoading(false);
    }
  };

  // Handle form submission
  const handleSubmit = (e) => {
    e.preventDefault();
    if (!documentType) {
      toast.error("Please select a document type");
      return;
    }

    const selectedType = documentTypes.find(
      (type) => type.id === Number(documentType)
    );
    localStorage.setItem("selectedDocumentType", JSON.stringify(selectedType));

    router.push("/auth/step-verification/id-verification-files");
  };

  useEffect(() => {
    handleToken();
    fetchDocumentTypes();
  }, []);

  return (
    <div className="flex">
      <div className="left w-[40%] xl:w-[35%] 3xl:w-[30%] bg-agent-primary min-h-screen fixed hidden lg:block">
        <div className="left-content">
          <div className="content-part px-[70px] pt-[130px]">
            <div className="ps-[10px] xl:ps-[45px] 2xl:ps-[75px]">
              <h2 className="text-[26px] 2xl:text-[30px] font-bold text-white mb-[10px]">
                {t("authPages.welcomeText")}
              </h2>
              <p className="text-[14px] 2xl:text-[16px] font-medium text-[rgba(255,255,255,0.80)]">
                {t("authPages.welcomeSubText2")}
              </p>
            </div>
            <div className="mt-[80px] xl:mt-[123px]">
              <div className="w-full h-auto">
                <Image
                  src={authImage}
                  height={400}
                  width={400}
                  alt="auth image"
                  className="w-full h-auto"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
      <div className="right w-full lg:w-[60%] xl:w-[65%] 3xl:w-[70%] lg:rtl:mr-[40%] xl:rtl:mr-[35%] 3xl:rtl:mr-[30%] lg:ltr:ml-[40%] xl:ltr:ml-[35%] 3xl:ltr:ml-[30%] min-h-screen relative">
        <div className="absolute top-4 rtl:left-4 ltr:right-4 z-50">
          <LanguageDropdown />
        </div>
        <div className="right-content flex justify-center items-center min-h-screen pt-8 xl:pt-24 pb-8 xl:pb-24">
          <div className="min-w-full sm:min-w-[535px] mx-auto px-4 xl:px-0">
            <div>
              <Link
                href={landingUrl}
                className={`logo block h-[${siteLogoHeight}px] w-auto mb-[40px]`}
              >
                {siteLogo ? (
                  <Image
                    src={siteLogo}
                    unoptimized
                    alt="logo"
                    width={205}
                    height={50}
                    style={{ height: `${siteLogoHeight}px`, width: "auto" }}
                    className="h-full"
                  />
                ) : (
                  <div className="h-[30px] w-[100px] bg-gray-100 animate-pulse rounded"></div>
                )}
              </Link>
              <h3 className="text-[22px] sm:text-[24px] md:text-[30px] font-bold text-agent-text mb-[30px] md:mb-[50px]">
                {t("authPages.agentRegister")}
              </h3>
              <div className="mb-[30px] md:mb-[50px]">
                <Image
                  src={line}
                  height={100}
                  width={100}
                  alt="element"
                  className="w-full h-auto"
                />
              </div>
              <div className="auth-gradient-color p-[10px] mb-[30px] md:mb-[50px]">
                <p className="text-[16px] md:text-[18px] font-bold text-agent-text text-center">
                  {t("authPages.chooseIdTypeTitle")}
                </p>
              </div>
              <div className="w-full">
                <form className="w-full" onSubmit={handleSubmit}>
                  <div className="grid grid-cols-12 gap-3.5 sm:gap-5">
                    <div className="col-span-12">
                      <label className="user-label">
                        {t("authPages.documentType")}{" "}
                        <span className="text-red-500">*</span>
                      </label>
                      <Select
                        value={documentType}
                        onValueChange={(value) => setDocumentType(value)}
                        disabled={documentTypeLoading}
                      >
                        <SelectTrigger className="w-full !h-[52px] border border-[rgba(12,3,16,0.2)] rounded-[30px] text-agent-text">
                          <SelectValue
                            placeholder={
                              documentTypeLoading
                                ? t("authPages.loading")
                                : t("authPages.selectType")
                            }
                          />
                        </SelectTrigger>
                        <SelectContent className="rounded-[16px]">
                          <SelectGroup>
                            <SelectLabel>
                              {t("authPages.selectType")}
                            </SelectLabel>
                            {documentTypes.map((type) => (
                              <SelectItem key={type.id} value={String(type.id)}>
                                {type.name}
                              </SelectItem>
                            ))}
                          </SelectGroup>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>

                  <div className="flex justify-between gap-3.5 mt-5 sm:mt-[30px] lg:mt-[40px]">
                    <button
                      type="submit"
                      className="group primary-button w-full"
                    >
                      <span className="primary-button-hover-effect"></span>
                      <span className="primary-button-text">
                        {t("authPages.next")}
                      </span>
                    </button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
        <div className="auth-elements">
          <div className="elem1 absolute top-0 rtl:right-0 ltr:left-0 z-[-1]">
            <Image
              src={element1}
              height={100}
              width={100}
              alt="element"
              className="w-[500px] 3xl:w-[610px] h-auto rtl:rotate-180 rtl:scale-y-[-1]"
            />
          </div>
          <div className="elem2 absolute top-0 rtl:left-0 ltr:right-0 hidden sm:block">
            <Image
              src={element2}
              height={100}
              width={100}
              alt="element"
              className="w-[170px] 3xl:w-[223px] h-auto rtl:rotate-180"
            />
          </div>
          <div className="elem3 absolute bottom-0 rtl:right-0 ltr:left-0 hidden lg:block">
            <Image
              src={element3}
              height={100}
              width={100}
              alt="element"
              className="w-[170px] 3xl:w-[223px] h-auto rtl:rotate-180"
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default IdVerificationChoose;
