import Select from "react-select";
import Input from "./input";
import {
  Control,
  Controller,
  FieldErrors,
  FieldValues,
  Path,
  PathValue,
  UseFormRegister,
  UseFormSetValue,
} from "react-hook-form";
import useSWR from "swr";
import { getComunas } from "@/utils/actions";
import { useEffect } from "react";

type ComunaSelectProps<T extends FieldValues> = {
  register: UseFormRegister<T>;
  errors: FieldErrors<T>;
  control: Control<T>;
  setValue: UseFormSetValue<T>;
};

const ComunaSelect = <T extends FieldValues>({ register, errors, control, setValue }: ComunaSelectProps<T>) => {
  const { data, isLoading } = useSWR("/comunas", getComunas);
  const noData = data?.length === 0 && !isLoading;

  useEffect(() => {
    noData && setValue("comuna" as Path<T>, "-" as PathValue<T, Path<T>>);
  }, [noData, setValue]);

  return (
    <Input label="Comuna" name={"comuna" as Path<T>} register={register} errors={errors} className="mb-7">
      <Controller
        control={control}
        name={"comuna" as Path<T>}
        render={({ field: { onChange }, fieldState: { invalid } }) => (
          <Select
            isLoading={isLoading}
            options={data?.map((comuna) => ({ value: comuna.codigo, label: comuna.nombre }))}
            isSearchable
            placeholder="Ej: Aisén"
            menuPlacement="top"
            isDisabled={noData}
            onChange={(e) => onChange(e?.value.toString())}
            isClearable
            classNames={{
              placeholder: () => "!text-[1rem] !text-dark-gray",
              singleValue: () => `!text-shark text-[1rem] pl-1.5`,
              control: (state) => `
                !h-[2.625rem] !border ${invalid ? "!border-red-500" : "!border-alto"} ${
                state.isFocused ? "![box-shadow:0_0_0_0.125rem_rgb(1_157_244)]" : "!shadow-none"
              } ${state.isFocused && invalid ? "![box-shadow:0_0_0_1px_rgb(220_38_38)]" : ""}`,
              option: (state) => `!py-1 ${state.isSelected ? "!bg-light-blue" : ""}`,
            }}
          />
        )}
      />
    </Input>
  );
};

export default ComunaSelect;
