import { FormEventHandler, useCallback } 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 { useShippingAddressForm } from '../hooks/useShippingAddressForm';
import { _useScopedI18n } from "../i18n/client";
import { countriesStore } from "../stores/countriesStore";
import { useFormStore } from "../stores/formStore";
import { SelectCities } from "./SelectCities";
import { SelectStates } from "./SelectStates";

export type AddressShippingFormComponentProps = {
  formId: string;
  isLoading: boolean;
  proceedSubmit: FormEventHandler<HTMLButtonElement>;
  onCancel?: () => void;
  enforceCheckoutEnabled?: boolean;
};

export default function AddressShippingFormComponent({
  formId,
  isLoading,
  proceedSubmit,
  enforceCheckoutEnabled = false,
}: AddressShippingFormComponentProps) {
  //
  const scopeT = _useScopedI18n("sharedComponents.addressFormComponent");

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

  const {
    shippingStates,
    shippingCities,
    loading,
    loadingCities,
    setLoading,
    setShippingLoadingCities,
  } = countriesStore();

  const { getShippingStatesByCountry, getShippingCityByStateAndCountry } =
    useAddressForm();

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

  const handleGetState = useCallback(
    async (country: number) => {
      setLoading(true);
      setShippingLoadingCities(true);
      const data = await getShippingStatesByCountry.mutateAsync(country);

      if (data && data?.length > 0) {
        setShippingLoadingCities(false);
      } else {
        handleGetCities({
          countryId: country,
        });
      }
    },
    [
      setLoading,
      setShippingLoadingCities,
      handleGetCities,
      getShippingStatesByCountry,
    ],
  );

  return (
    <>
      <form action="" method="post">
        <div className="grid grid-cols-12 gap-y-4 md:gap-y-7 md:gap-x-5 mb-5">
          <div className="col-span-12 md:col-span-6 relative">
            <Inputfield
              title={`${scopeT("firstName")} *`}
              placeholder={scopeT("firstName")}
              className={undefined}
              value={undefined}
              readOnly={undefined}
              name="firstName"
              formId={formId}
            />
          </div>
          <div className="col-span-12 md:col-span-6 relative">
            <Inputfield
              title={`${scopeT("lastName")} *`}
              className={undefined}
              placeholder={scopeT("lastName")}
              value={undefined}
              readOnly={undefined}
              name="lastName"
              formId={formId}
            />
          </div>
          <div className="col-span-12 relative">
            <Inputfield
              title={`${scopeT("address")} *`}
              className={undefined}
              placeholder={scopeT("address")}
              value={undefined}
              readOnly={undefined}
              name="address"
              formId={formId}
            />
          </div>
          <div className="col-span-12 relative">
            <Inputfield
              title={`${scopeT("flatHouseBuilding")}`}
              className={undefined}
              placeholder={`${scopeT("flatHouseBuilding")}`}
              value={undefined}
              readOnly={undefined}
              name="buildingInfo"
              formId={formId}
            />
          </div>
          <div className="col-span-12 md:col-span-6 relative">
            <SelectCountries
              title={`${scopeT("selectCountry")} *`}
              className={undefined}
              placeholder={scopeT("selectCountry")}
              name="countryId"
              formId={formId}
              onCountrySelected={handleGetState}
              forShipping={true}
              enforceCheckoutEnabled={enforceCheckoutEnabled}
            />
          </div>
          <div className="col-span-12 md:col-span-6 relative">
            {shippingStates?.length > 0 && countryIdField ? (
              <SelectStates
                title={`${scopeT("state")} *`}
                className={undefined}
                placeholder={scopeT("state")}
                name="state"
                formId={formId}
                onStateSelected={handleGetCities}
                forShipping={true}
              />
            ) : (
              <Inputfield
                title={`${scopeT("state")} *`}
                className={undefined}
                placeholder={scopeT("state")}
                value={undefined}
                readOnly={loading}
                name="state"
                formId={formId}
                disabled={loading}
              />
            )}
          </div>
          <div className="col-span-12 md:col-span-6 relative">
            {shippingCities?.length > 0 && countryIdField ? (
              <SelectCities
                title={`${scopeT("city")} *`}
                className={undefined}
                placeholder={scopeT("city")}
                name="city"
                formId={formId}
                forShipping={true}
              />
            ) : (
              <Inputfield
                title={`${scopeT("city")} *`}
                className={undefined}
                placeholder={scopeT("city")}
                value={undefined}
                readOnly={loading}
                name="city"
                formId={formId}
                disabled={loadingCities}
              />
            )}
          </div>
          <div className="col-span-12 md:col-span-6 relative">
            <Inputfield
              title={`${scopeT("zipCode")} *`}
              className={undefined}
              placeholder={
                zipCodeExampleField?.length > 0
                  ? zipCodeExampleField
                  : scopeT("zipCode")
              }
              value={undefined}
              readOnly={undefined}
              name="postalCode"
              formId={formId}
              format={
                zipCodeExampleField?.length > 0 ? zipCodeExampleField : null
              }
            />
          </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=""
            icon={undefined}
            type="submit"
            onClick={proceedSubmit}
            loading={isLoading}
            disabled={isLoading}
          >
            {scopeT("submitBtn")}
          </ButtonCustom>
        </div>
      </form>
    </>
  );
}
