"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 LoadingSpinner from "@/components/common/LoadingSpinner";
import LanguageDropdown from "@/components/dashboard/UserDropdown/LanguageDropdown";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Spinner } from "@/components/ui/spinner";
import { useRegisterInfo } from "@/context/RegisterInfoContext";
import { useSettings } from "@/context/settingsContext";
import { useT } from "@/context/TranslationContext";
import ApiPath from "@/network/api/apiPath";
import NetworkService from "@/network/service/networkService";
import { getFieldStatus, getSettingValue } from "@/utils/utils";
import { Icon } from "@iconify/react";
import Cookies from "js-cookie";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "react-toastify";

const RegisterPersonalInfoTwo = () => {
  const network = new NetworkService();
  const [allCountry, setAllCountry] = useState([]);
  const [countryLoading, setCountryLoading] = useState(false);
  const [country, setCountry] = useState("");
  const [phone, setPhone] = useState("");
  const [referralCode, setReferralCode] = useState("");
  const [termsAndConditions, setTermsAndConditions] = useState(false);
  const [registerFieldsValidation, setRegisterFieldsValidation] = useState([]);
  const [loading, setLoading] = useState(true);
  const [submitLoading, setSubmitLoading] = useState(false);
  const {
    personalInfo,
    additionalInfo,
    setAdditionalInfo,
    clearRegistrationData,
  } = useRegisterInfo();
  const router = useRouter();
  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();

  // Fetch all countries
  const fetchAllCountry = async () => {
    try {
      setCountryLoading(true);
      const res = await network.globalGet(ApiPath.allCountry);
      if (res.status === "completed") {
        setAllCountry(res.data.data);
      }
    } finally {
      setCountryLoading(false);
    }
  };

  // Fetch field validation settings
  const getRegisterFieldsValidation = async () => {
    setLoading(true);
    try {
      const res = await network.globalGet(ApiPath.registerFieldsValidation);
      if (res.status === "completed") {
        setRegisterFieldsValidation(res.data.data);
      }
    } finally {
      setLoading(false);
    }
  };

  // Field visibility and validation configuration
  const fieldSettings = {
    username: {
      show: getFieldStatus(registerFieldsValidation, "agent_username_show"),
      required: getFieldStatus(
        registerFieldsValidation,
        "agent_username_validation"
      ),
    },
    country: {
      show: getFieldStatus(registerFieldsValidation, "agent_country_show"),
      required: getFieldStatus(
        registerFieldsValidation,
        "agent_country_validatio"
      ),
    },
    phone: {
      show: getFieldStatus(registerFieldsValidation, "agent_phone_show"),
      required: getFieldStatus(
        registerFieldsValidation,
        "agent_phone_validation"
      ),
    },
    referralCode: {
      show: getFieldStatus(registerFieldsValidation, "referral_code_show"),
      required: getFieldStatus(
        registerFieldsValidation,
        "referral_code_validation"
      ),
    },
    gender: {
      show: getFieldStatus(registerFieldsValidation, "gender_show"),
      required: getFieldStatus(registerFieldsValidation, "gender_validation"),
    },
  };

  // Load saved values
  useEffect(() => {
    if (additionalInfo.country) setCountry(additionalInfo.country);
    if (additionalInfo.phone) setPhone(additionalInfo.phone);
    if (additionalInfo.referralCode)
      setReferralCode(additionalInfo.referralCode);
  }, [additionalInfo]);

  // Dynamic form validation
  const validateForm = () => {
    if (fieldSettings.country.required && !country) {
      toast.error("Please select your country");
      return false;
    } else if (fieldSettings.phone.required && !phone) {
      toast.error("Please enter your phone number");
      return false;
    } else if (!termsAndConditions) {
      toast.error("Please check the terms and conditions");
      return false;
    }
    return true;
  };

  // Handle final submit
  const handlePersonalInfoSubmit = async (e) => {
    e.preventDefault();
    if (!validateForm()) return;

    setAdditionalInfo({ country, phone, referralCode });

    try {
      const requestBody = {
        first_name: personalInfo.first_name,
        last_name: personalInfo.last_name,
      };

      if (fieldSettings.username.required || personalInfo.username) {
        requestBody.username = personalInfo.username.trim();
      }

      if (fieldSettings.gender.required || personalInfo.gender) {
        requestBody.gender = personalInfo.gender.trim();
      }

      if (fieldSettings.country.required || country) {
        requestBody.country = country.trim();
      }

      if (fieldSettings.phone.required || phone) {
        requestBody.phone = phone.trim();
      }

      if (fieldSettings.referralCode.required || referralCode) {
        requestBody.invite = referralCode.trim();
      }

      setSubmitLoading(true);
      const res = await network.post(ApiPath.updatePersonalInfo, requestBody);
      if (res.status === "completed") {
        toast.success(res.data.message);
        // Save cookie
        Cookies.set("personalInfo", "true");
        router.push("/auth/step-verification/success-status");
      }
    } finally {
      setSubmitLoading(false);
    }
  };

  // Effects
  useEffect(() => {
    fetchAllCountry();
    getRegisterFieldsValidation();
  }, []);

  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.moreInformation")}
                </p>
              </div>
              <div className="w-full">
                {loading ? (
                  <div className="flex items-center justify-center min-h-[300px]">
                    <LoadingSpinner />
                  </div>
                ) : (
                  <form onSubmit={handlePersonalInfoSubmit}>
                    <div className="grid grid-cols-12 gap-3.5 sm:gap-5">
                      {fieldSettings.country.show && (
                        <div className="col-span-12">
                          <div className="relative">
                            <Select
                              disabled={countryLoading}
                              value={country}
                              onValueChange={(value) => setCountry(value)}
                            >
                              <div className="absolute rtl:right-[16px] ltr:left-[16px] top-[50%] -translate-y-1/2">
                                <Icon
                                  icon="hugeicons:earth"
                                  width="24"
                                  height="24"
                                  className="w-[18px] h-[18px] text-[#9E9A9F]"
                                />
                              </div>

                              <div className="absolute rtl:right-[42px] ltr:left-[42px] top-[50%] -translate-y-1/2">
                                <span className="block w-[2px] h-[14px] bg-[rgba(12,3,16,0.20)]"></span>
                              </div>

                              <SelectTrigger className="w-full !h-[52px] border border-[rgba(12,3,16,0.2)] rounded-[30px] text-agent-text ps-[52px]">
                                <SelectValue
                                  placeholder={
                                    countryLoading
                                      ? t("placeholder.loading")
                                      : t("placeholder.selectCountry")
                                  }
                                />
                              </SelectTrigger>
                              <SelectContent className="rounded-[16px]">
                                <SelectGroup>
                                  <SelectLabel>Select Country</SelectLabel>
                                  {allCountry.map((countryItem) => (
                                    <SelectItem
                                      key={countryItem.code}
                                      value={`${countryItem.dial_code}:${countryItem.code}`}
                                    >
                                      {countryItem.name}
                                    </SelectItem>
                                  ))}
                                </SelectGroup>
                              </SelectContent>
                            </Select>
                          </div>
                        </div>
                      )}
                      {fieldSettings.phone.show && (
                        <div className="col-span-12">
                          <div>
                            <div className="relative">
                              <input
                                type="text"
                                id="phone"
                                name="phone"
                                placeholder={t("label.phone")}
                                className={`user-input user-input-left peer`}
                                value={phone}
                                onChange={(e) => setPhone(e.target.value)}
                              />
                              <div className="icon absolute top-[50%] -translate-y-1/2 rtl:right-4 ltr:left-4">
                                <Icon
                                  icon="hugeicons:call-02"
                                  width="24"
                                  height="24"
                                  className="w-[18px] h-[18px] text-[#9E9A9F]"
                                />
                              </div>
                              <div className="absolute top-[50%] -translate-y-1/2 rtl:right-[42px] ltr:left-[42px]">
                                <span className="block w-[2px] h-[16px] bg-[rgba(12,3,16,0.20)]"></span>
                              </div>
                            </div>
                          </div>
                        </div>
                      )}
                      <div className="col-span-12">
                        <div className="flex items-center gap-2">
                          <input
                            type="checkbox"
                            className="checkbox-colored"
                            id="colored-checkbox"
                            checked={termsAndConditions}
                            onChange={(e) =>
                              setTermsAndConditions(e.target.checked)
                            }
                          />
                          <label
                            htmlFor="colored-checkbox"
                            className="text-[14px] text-agent-paragraph font-semibold cursor-pointer"
                          >
                            {t("authPages.iAgree")}{" "}
                            <Link
                              href="/terms-and-conditions"
                              className="text-agent-primary"
                            >
                              {t("authPages.termsAndConditions")}
                            </Link>
                          </label>
                        </div>
                      </div>
                    </div>
                    <div className="flex justify-between gap-3.5 mt-[30px] lg:mt-[40px]">
                      <Link
                        href="/auth/step-verification/setup-personal-info"
                        className="group primary-button primary-border w-full"
                      >
                        <span className="primary-button-hover-effect"></span>
                        <span className="primary-button-text">
                          {t("authPages.back")}
                        </span>
                      </Link>
                      <button
                        type="submit"
                        className="group primary-button w-full"
                        disabled={submitLoading}
                      >
                        <span className="primary-button-hover-effect"></span>
                        <span className="primary-button-text">
                          {submitLoading ? (
                            <div className="flex items-center gap-2">
                              <Spinner />
                              {t("authPages.submitting")}
                            </div>
                          ) : (
                            t("authPages.submit")
                          )}
                        </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 RegisterPersonalInfoTwo;
