/* eslint-disable @typescript-eslint/no-explicit-any */
import { useEffect, useState } from "react";
import Select from "react-select";
import CreatableSelect from "react-select/creatable";
import { getList } from "../../Api/MastersApi";

export interface OptionType {
  value: string | number;
  label: string;
  code?: string;
  name?: string;
  id?: string | number;
}

interface SearchableSelectProps {
  optionsData?: OptionType[];
  apiUrl?: string;
  name: string;
  value?: OptionType | OptionType[] | null;
  onChange: (
    value: OptionType | OptionType[] | null,
    name: string
  ) => void;
  placeholder?: string;
  isMulti?: boolean;
  isDisabled?: boolean;
  isClearable?: boolean;
  addNew?: boolean;
}

function SearchableSelect({
  optionsData,
  apiUrl,
  name,
  value = null,
  onChange,
  placeholder = "",
  isMulti = false,
  isDisabled = false,
  isClearable = true,
  addNew = false,
}: SearchableSelectProps) {
  const [options, setOptions] = useState<OptionType[]>([]);
  const [loading, setLoading] = useState(false);
  const [inputValue, setInputValue] = useState("");

  const SelectComponent = addNew ? CreatableSelect : Select;

  const formatLabel = (opt: OptionType) =>
    opt.code && opt.name && opt.code !== opt.name
      ? `${opt.code} - ${opt.name}`
      : opt.label || opt.name || String(opt.value);

  useEffect(() => {
    if (optionsData) {
      setOptions(optionsData);
      return;
    }

    if (!apiUrl) return;

    setLoading(true);
    getList(apiUrl, { search: inputValue })
      .then((res) => {
        if (res?.status && Array.isArray(res.data)) {
          setOptions(
            res.data.map((item: any) => ({
              value: item.id,
              label: item.name,
              code: item.code,
              name: item.name,
              id: item.id,
            }))
          );
        }
      })
      .finally(() => setLoading(false));
  }, [apiUrl, inputValue, optionsData]);

  return (
    <SelectComponent
      name={name}
      options={options}
      value={value}
      isMulti={isMulti}
      isDisabled={isDisabled}
      isClearable={isClearable}
      isLoading={loading}
      placeholder={placeholder}
      onChange={(val) => onChange(val as any, name)}
      onInputChange={(val) => {
        setInputValue(val);
        return val;
      }}
      getOptionLabel={formatLabel}
      getOptionValue={(opt) => String(opt.value)}
      styles={{
        control: (base) => ({
          ...base,
          minHeight: "44px",
          fontSize: "13px",
          borderRadius: "10px",
          padding: "0 8px", // ✅ FIXED
        }),
        valueContainer: (base) => ({
          ...base,
          padding: "2px 8px", // ✅ FIXED
        }),
        input: (base) => ({
          ...base,
          margin: 0,
          padding: 0,
        }),
        placeholder: (base) => ({
          ...base,
          margin: 0,
          color: "#9ca3af",
        }),
        indicatorsContainer: (base) => ({
          ...base,
          paddingRight: "6px",
        }),
        option: (base, state) => ({
          ...base,
          backgroundColor: state.isFocused ? "#f3f4f6" : "#fff",
          color: "#111827",
          cursor: "pointer",
        }),
      }}
    />
  );
}

export default SearchableSelect;
