import { Typography } from "@material-tailwind/react";
import React, { useMemo } from "react";
import {
  HTMLInputTypeAttribute,
  useCallback,
  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 { SelectWithSearch } from "./SelectComponent";

export interface InputFieldProps {
  title: string;
  placeholder?: string;
  type?: HTMLInputTypeAttribute;
  name?: string;
  forShipping?: boolean;
  formId: string;
  onStateSelected?: (value: number | string | any) => void;
}

export function SelectStates({
  className,
  title,
  placeholder,
  name,
  formId,
  onStateSelected,
  forShipping = false,
}) {
  const { states, shippingStates, setCities, setShippingCities } =
    countriesStore();
  const filteredStates = useMemo(() => {
    return forShipping ? shippingStates : states;
  }, [states, shippingStates, forShipping]);
  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 fieldKey = name ?? title?.toLowerCase();

  const watchField = watch?.(`${fieldKey}`);
  const formValues = watch?.();

  const checkError = useCallback(() => {
    if (errors?.[fieldKey]) {
      setError(errors[fieldKey]);
    } else {
      setError(null);
    }
  }, [errors, fieldKey]);

  useEffect(() => {
    setTimeout(() => {
      checkError();
    }, 100);
  }, [watchField, checkError]);

  const handleOnChange = (value: any) => {
    setValue(`${fieldKey}`, +value.id, {
      shouldValidate: true,
    });
    if (forShipping) {
      setShippingCities([]);
    } else {
      setCities([]);
    }
    setValue("city", "");
    onStateSelected({
      stateId: value.id,
      countryId: formValues.countryId,
    });
  };

  if (!reactHookUseForm || !register) return <></>;

  return (
    <>
      <Typography
        variant="lead"
        className="text-xs font-medium text-black-400 mb-1"
      >
        {renderTitleWithRedAsterisk(title)}
      </Typography>

      <SelectWithSearch
        maxHeightOpened={235}
        className={` p-3
                    w-full min-w-full h-10 text-base
                    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 !border-t-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={filteredStates}
        searchKey="name"
        placeholder={placeholder}
        renderOption={(_item, state) => {
          if (state)
            return (
              <div
                key={state.id}
                className={
                  state.id === watchField
                    ? "flex items-center gap-2 pointer-events-none text-xs font-normal"
                    : "flex items-center gap-2 text-xs font-normal"
                }
              >
                {state.name}
              </div>
            );
        }}
        value={
          filteredStates?.find((item) => item.id === watchField) ||
          filteredStates?.find((item) => item.name === watchField) ||
          null
        }
        setValue={(value) => {
          handleOnChange(value);
        }}
      />
      {error && (
        <Typography
          variant="lead"
          className="text-red-500 font-normal text-xs  px-1 block md:absolute -bottom-[1.1rem] left-0"
        >
          {error?.message}
        </Typography>
      )}
    </>
  );
}
