import {
  Button,
  Menu,
  MenuHandler,
  MenuItem,
  MenuList,
  Typography,
} from "@material-tailwind/react";
import React, { useEffect, useState } from "react";
import { UseFormReturn } from "react-hook-form";
import { IoChevronDownOutline } from "react-icons/io5";

import { _useScopedI18n } from "../i18n/client";
import { countriesStore } from "../stores/countriesStore";
import { useFormStore } from "../stores/formStore";
import { renderTitleWithRedAsterisk } from "../utils/app.util";
import CustomNextImage from "./CustomNextImage";
import Inputfield from "./Inputfield";

export function PhoneNumberCountries({
  formId,
  fieldName,
}: {
  formId: string;
  fieldName: string;
}) {
  const scopeT = _useScopedI18n("sharedComponents.phoneNumberComponent");

  const { countries } = countriesStore();
  const [country, setCountry] = React.useState(0);
  const [selectedCallingCode, setSelectedCallingCode] = useState<number>();

  const { reactHookUseForm } = useFormStore();
  const form = (reactHookUseForm as { [key: string]: UseFormReturn<any> })?.[
    formId
  ];
  const setValue = form?.setValue;
  const watch = form?.watch;
  const fieldKey = fieldName ?? fieldName?.toLowerCase();

  const watchCountryIdField = watch?.(`countryId`);

  const handleOnChange = (code: number, index: number) => {
    if (!setValue) return;

    setCountry(index);
    setTimeout(() => {
      setValue(`${fieldKey}`, code, {
        shouldValidate: true,
      });

      setSelectedCallingCode(code);
      const selectedCountry = countries?.find((c) => +c.callingCode == code);
      setValue("minPhoneLength", selectedCountry.minPhoneLength);
    }, 250);
  };

  useEffect(() => {
    if (!setValue || !countries?.length) return;

    const selectedCountry = countries?.find(
      (c) => c.id == +watchCountryIdField,
    );
    const { callingCode, minPhoneLength } =
      selectedCountry ?? countries?.[country];

    (async () => await setSelectedCallingCode(+callingCode))();

    setValue(`${fieldKey}`, +callingCode, {
      shouldValidate: true,
    });
    setValue("minPhoneLength", minPhoneLength);
  }, [fieldKey, countries, country, watchCountryIdField, setValue]);

  return (
    <>
      <Typography
        variant="lead"
        className="text-xs font-medium text-black-400 mb-1"
      >
        {renderTitleWithRedAsterisk(`${scopeT("title")} *`)}
      </Typography>
      <div className="relative flex items-center w-auto z-90 mobileNumberField">
        <Menu placement="bottom-start">
          <MenuHandler>
            <Button
              ripple={false}
              variant="text"
              className="mt-1 p-3 text-sm flex items-center justify-between h-10 font-medium gap-x-1.5 rounded-md border border-r-0 rounded-r-none border-slate-100  bg-slate-50/60 hover:bg-slate-50 focus:bg-slate-50 active:bg-slate-50/60  whitespace-nowrap"
            >
              <div>+{selectedCallingCode}</div>
              <div className="h-5 w-3">
                <IoChevronDownOutline className="text-black-400 h-5 w-4 text-base" />
              </div>
            </Button>
          </MenuHandler>
          <MenuList className=" absolute max-h-[20rem] max-w-[18rem] z-[999999]">
            {countries?.map((Item, index): any => {
              return (
                <MenuItem
                  key={Item.name}
                  value={Item.name}
                  className="flex items-center gap-2"
                  onClick={() => handleOnChange(+Item.callingCode, index)}
                >
                  <CustomNextImage
                    src={Item.flag}
                    alt={Item.name}
                    className="h-4 w-5 rounded-sm object-cover"
                    height={30}
                    width={30}
                  />
                  {Item.name}{" "}
                  <span className="ml-auto">{Item.callingCode}</span>
                </MenuItem>
              );
            })}
          </MenuList>
        </Menu>
        <Inputfield
          title={""}
          type="number"
          className="rounded-l-none flex-1"
          placeholder={"00 - 000 - 000"}
          value={undefined}
          readOnly={undefined}
          name="phone"
          formId={formId}
        />
      </div>
    </>
  );
}
