import { TextUtil } from "@greatness/util";
import { memo, useCallback } from "react";
import { Controller, useFormContext } from "react-hook-form";

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "../../ui/select";

import type { SelectInputValue } from "./types";

const SelectInput: React.FC<{
  data: SelectInputValue[];
  isLoading?: boolean;
  label: string;
  maxHeight?: number;
  name: string;
  popupIcon?: React.ReactNode;
  // @ts-expect-error check later
}> = ({ name, label, data, isLoading = false, maxHeight = 250 }) => {
  const { setValue, watch, control } = useFormContext();
  const [currentValue] = watch([name]);

  const onChange = useCallback(
    (newInputValue: string) => {
      setValue(name, newInputValue, {
        shouldDirty: true,
        shouldValidate: true,
      });
    },
    [name, setValue],
  );

  return (
    <Controller
      control={control}
      name={name}
      render={() => {
        return (
          <Select
            value={currentValue}
            onValueChange={(newInputValue) => {
              onChange(newInputValue);
            }}
          >
            <SelectTrigger className="w-full">
              <SelectValue
                placeholder={TextUtil.isEmpty(label) ? "" : label}
              >
                {/** biome-ignore lint/suspicious/noDoubleEquals: <explanation> todo*/}
                {data.find((a) => a.value == currentValue)?.label ?? ""}
              </SelectValue>
            </SelectTrigger>
            <SelectContent>
              {data
                .filter((a) => a.value !== "")
                .map((a) => (
                  <SelectItem key={a.value as string} value={a.value as string}>
                    {a.label}
                  </SelectItem>
                ))}
            </SelectContent>
          </Select>
        );
      }}
    />
  );
};

export default memo(SelectInput);
