import { FormEventHandler, useCallback, useEffect, useState } from "react";
import { UseFormReturn } from "react-hook-form";

import ButtonCustom from "../components/Button";
import Inputfield from "../components/Inputfield";
import { PhoneNumberCountries } from "../components/PhoneNumberCountries";
import { SelectCountries } from "../components/SelectCountries";
import { useAddressForm } from "../hooks/useAddressForm";
import { _useScopedI18n } from "../i18n/client";
import { countriesStore } from "../stores/countriesStore";
import { useFormStore } from "../stores/formStore";
import { UserAddress } from "../types/cart";
import { SelectCities } from "./SelectCities";
import { SelectStates } from "./SelectStates";

export type EditAddressFormComponentProps = {
  formId: string;
  isLoading: boolean;
  forShipping?: boolean;
  proceedSubmit: FormEventHandler<HTMLButtonElement>;
  selectedAddress?: UserAddress[];
  onCancel?: () => void;
};

export default function EditAddressFormComponent({
  formId,
  isLoading,
  proceedSubmit,
  selectedAddress,
  forShipping = false,
}: EditAddressFormComponentProps) {
  const scopeT = _useScopedI18n("sharedComponents.addressFormComponent");

  const [fieldValue, setFieldValue] = useState(selectedAddress || {});

  const { reactHookUseForm } = useFormStore();
  const { watch } =
    (reactHookUseForm as { [key: string]: UseFormReturn<any> })?.[formId] ?? {};
  const countryIdField = watch?.(`countryId`);
  const zipCodeExampleField = watch?.(`zipCodeExample`);

  const {
    states,
    cities,
    loading,
    loadingCities,
    setLoading,
    setLoadingCities,
  } = countriesStore();

  const { getStatesByCountry, getCityByStateAndCountry } = useAddressForm();

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFieldValue((prevValue) => ({
      ...prevValue,
      [name]: value, // Dynamically update the field based on its name
    }));
  };

  // const { countries } = countriesStore();
  // const selectedCountry = countries.find((country) => country.id === countryIdField);

  const handleGetCities = useCallback(
    (state: any) => {
      setLoadingCities(true);
      getCityByStateAndCountry.mutate(state);
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );

  const handleGetState = useCallback(
    async (country: number) => {
      setFieldValue((prevValue) => ({
        ...prevValue,
        city: null,
        state: null,
      }));
      setLoading(true);
      setLoadingCities(true);

      const data = await getStatesByCountry.mutateAsync(country);
      if (data && data?.length > 0) {
        setLoadingCities(false);
      } else {
        handleGetCities({
          countryId: country,
        });
      }
    },
    [setLoading, setLoadingCities, handleGetCities, getStatesByCountry],
  );

  const handleStateFromTheOldAddress = useCallback(
    async () => {
      await handleGetState(fieldValue?.["country"]?.id);
      setLoadingCities(true);
      await getCityByStateAndCountry.mutateAsync({
        countryId: fieldValue?.["country"]?.id,
        stateId: states?.find((item) => item?.name === fieldValue?.["state"])
          ?.id,
      });
      setLoadingCities(false);
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );

  useEffect(() => {
    handleStateFromTheOldAddress();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <>
      <form action="" method="post">
        <div className="grid grid-cols-12 gap-y-4 md:gap-y-4 md:gap-x-4 mb-5">
          <div className="col-span-12 md:col-span-6 relative">
            <Inputfield
              title={`${scopeT("firstName")} *`}
              placeholder={scopeT("firstName")}
              name="firstName"
              formId={formId}
              value={fieldValue["firstName"] || ""}
              onChange={handleChange}
            />
          </div>
          <div className="col-span-12 md:col-span-6 relative">
            <Inputfield
              title={`${scopeT("lastName")} *`}
              placeholder={scopeT("lastName")}
              name="lastName"
              formId={formId}
              value={fieldValue["lastName"] || ""}
              onChange={handleChange}
            />
          </div>
          <div className="col-span-12 relative">
            <Inputfield
              title={`${scopeT("address")} *`}
              placeholder={scopeT("address")}
              name="address"
              formId={formId}
              value={fieldValue["address"] || ""}
              onChange={handleChange}
            />
          </div>
          <div className="col-span-12 relative">
            <Inputfield
              title={`${scopeT("flatHouseBuilding")}`}
              placeholder={`${scopeT("flatHouseBuilding")}`}
              name="buildingInfo"
              formId={formId}
              value={fieldValue["buildingInfo"] || ""}
              onChange={handleChange}
            />
          </div>
          <div className="col-span-12 md:col-span-6 relative">
            <SelectCountries
              title={`${scopeT("selectCountry")} *`}
              placeholder={scopeT("selectCountry")}
              name="countryId"
              formId={formId}
              onCountrySelected={handleGetState}
              className={undefined}
              forShipping={forShipping}
            />
          </div>
          <div className="col-span-12 md:col-span-6 relative">
            {states?.length > 0 && countryIdField ? (
              <SelectStates
                title={`${scopeT("state")} *`}
                className={undefined}
                placeholder={scopeT("state")}
                name="state"
                formId={formId}
                onStateSelected={handleGetCities}
              />
            ) : (
              <Inputfield
                title={`${scopeT("state")} *`}
                className={undefined}
                placeholder={scopeT("state")}
                name="state"
                formId={formId}
                disabled={loading}
                value={fieldValue["state"] || ""}
                onChange={handleChange}
              />
            )}
          </div>
          <div className="col-span-12 md:col-span-6 relative">
            {cities?.length > 0 && countryIdField ? (
              <SelectCities
                title={`${scopeT("city")} *`}
                className={undefined}
                placeholder={scopeT("city")}
                name="city"
                formId={formId}
              />
            ) : (
              <Inputfield
                title={`${scopeT("city")} *`}
                className={undefined}
                placeholder={scopeT("city")}
                name="city"
                formId={formId}
                disabled={loadingCities}
                value={fieldValue["city"] || ""}
                onChange={handleChange}
              />
            )}
          </div>
          <div className="col-span-12 md:col-span-6 relative">
            <Inputfield
              title={`${scopeT("zipCode")} *`}
              className={undefined}
              name="postalCode"
              formId={formId}
              placeholder={
                zipCodeExampleField && zipCodeExampleField.length > 0
                  ? zipCodeExampleField
                  : scopeT("zipCode")
              }
              format={
                zipCodeExampleField && zipCodeExampleField.length > 0
                  ? zipCodeExampleField
                  : ""
              }
              value={fieldValue["postalCode"] || ""}
              onChange={handleChange}
            />
          </div>
          <div className="col-span-12 relative">
            <PhoneNumberCountries formId={formId} fieldName="countryCode" />
          </div>
        </div>
        <div className="flex gap-3 justify-end w-full">
          <ButtonCustom
            className="!text-sm !px-5 !py-3"
            icon={undefined}
            type="submit"
            onClick={proceedSubmit}
            loading={isLoading}
            disabled={isLoading}
          >
            {scopeT("updateBtn")}
          </ButtonCustom>
        </div>
      </form>
    </>
  );
}
