import { Typography } from "@material-tailwind/react";
import React from "react";
import { HTMLInputTypeAttribute, useEffect, useState } from "react";
import { UseFormReturn } from "react-hook-form";

import { countriesStore } from "../stores/countriesStore";
import { useFormStore } from "../stores/formStore";
import { renderTitleWithRedAsterisk } from "../utils/app.util";
import CustomNextImage from "./CustomNextImage";
import { SelectWithSearch } from "./SelectComponent";

export interface InputFieldProps {
  title: string;
  className?: string;
  placeholder?: string;
  type?: HTMLInputTypeAttribute;
  name?: string;
  formId: string;
  forShipping?: boolean;
  forPickUp?: boolean;
  /** When true, only countries with isCheckoutEnabled are shown (checkout flows). */
  enforceCheckoutEnabled?: boolean;
  onCountrySelected?: (value: string | number) => void;
}

export function SelectCountries({
  className,
  title,
  placeholder,
  name,
  formId,
  forShipping = true,
  forPickUp = false,
  enforceCheckoutEnabled = false,
  onCountrySelected,
}: InputFieldProps) {
  const {
    countries,
    shippingCountries,
    setStates,
    setShippingStates,
    setCities,
    setShippingCities,
    setStores,
    loading,
  } = countriesStore();

  const { reactHookUseForm } = useFormStore();

  const { register, formState, setValue, watch } =
    (reactHookUseForm as { [key: string]: UseFormReturn<any> })?.[formId] ?? {};

  const { errors } = formState ?? {};
  const [error, setError] = useState<any>(null);
  const [search, setSearch] = useState<string>("");

  const baseCountries =
    forShipping && shippingCountries?.length
      ? shippingCountries
      : countries;
  const checkoutFiltered = enforceCheckoutEnabled
    ? baseCountries?.filter((country) => country.isCheckoutEnabled !== false)
    : baseCountries;
  const filteredCountries = checkoutFiltered?.filter((country) =>
    country.name.toLowerCase().includes(search.toLowerCase()),
  );

  // Dynamic key for the field
  const fieldKey = name ?? title?.toLowerCase();

  // Watch field value
  const watchField = watch?.(`${fieldKey}`);

  // Error handling
  useEffect(() => {
    if (errors?.[fieldKey]) {
      (async () => await setError(errors[fieldKey]))();
    } else {
      (async () => await setError(null))();
    }
  }, [watchField, errors, fieldKey]);

  // Handle change logic for country selection
  const handleOnChange = (value: any) => {
    const countryId = +value.id; // Ensure it's a number
    const selectedCountry = checkoutFiltered?.find((c) => c.id === countryId);

    if (!selectedCountry) return; // Handle invalid selection safely

    // Update form state with selected country details
    setValue(`${fieldKey}`, countryId, { shouldValidate: true });
    if (forPickUp) {
      setValue("store", "");
      setStores([]);
    } else {
      setValue("city", "");
      setValue("state", "");
      setValue("zipCodeRegex", selectedCountry.zipCodeRegex);
      setValue("zipCodeExample", selectedCountry.zipCodeExample);
      setValue("postalCode", selectedCountry.zipCodeExists ? "" : "00000");
      setValue("minPhoneLength", selectedCountry.minPhoneLength);
      setValue("countryCode", selectedCountry.callingCode);

      // Reset related states and
      if (forShipping) {
        setShippingCities([]);
        setShippingStates([]);
      } else {
        setStates([]);
        setCities([]);
      }
    }

    // Notify parent via the callback
    if (onCountrySelected) {
      onCountrySelected(countryId);
    }

    // Clear the search input
    setSearch("");
  };

  // Render the component only if form hooks are available
  if (!reactHookUseForm || !register) return null;

  return (
    <>
      <Typography
        variant="lead"
        className="text-xs font-medium text-black-400 mb-1"
      >
        {renderTitleWithRedAsterisk(title)}
      </Typography>
      <SelectWithSearch
        maxHeightOpened={235}
        disabled={loading}
        className={`p-3
                    w-full min-w-full h-10 text-sm
                    bg-white rounded-md	
                    text-gray-900 
                    shadow-gray-200/5 
                    ring-4 ring-transparent 
                    placeholder:text-gray-300 placeholder:opacity-100 
                    !border !border-slate-100 !border-t-slate-100  
                    ${error ? "!border-red-500 ring-red-50 bg-red-100/10" : "!border-t-slate-100"} 
                    focus:!border-slate-300                  
                    focus:ring-gray-300/10 
                    focus:bg-offWhite
                    shadow-none ${className}
                `}
        items={filteredCountries ?? []}
        searchKey="name"
        placeholder={placeholder}
        renderOption={(_item, country) => {
          if (country)
            return (
              <div
                key={country.id}
                className={`flex items-center gap-2 text-xs font-normal ${
                  country.id === watchField ? "pointer-events-none" : ""
                }`}
              >
                <CustomNextImage
                  src={country.flag}
                  alt={country.name}
                  className="h-4 w-6 rounded-sm object-cover"
                  height={30}
                  width={30}
                />
                {country.name}
              </div>
            );
        }}
        value={
          filteredCountries?.find((item) => item.id === watchField) || null
        }
        setValue={(value) => handleOnChange(value)}
      />
      {error && (
        <Typography
          variant="lead"
          className="text-red-500 font-normal text-[0.6rem] px-1 block md:absolute -bottom-[1.1rem] left-0"
        >
          {error?.message}
        </Typography>
      )}
    </>
  );
}
