import { Form, Select } from "antd";
import React, { useState } from "react";
import useFormField from "../../../Hooks/useFormField";
import { MdOutlineEdit } from "react-icons/md";
import { translateOptions } from "../utils/translatedOptions";

const LocalSelectField = ({
  name,
  label,
  placeholder,
  isDisabled,
  option,
  isMulti,
  onChange,
  className,
  props,
  no_label,
  label_icon,
}: any) => {
  const { errorMsg, isError, t, formik } = useFormField(name, props);

  // State to manage the search input value
  const [searchValue, setSearchValue] = useState("");

  const handleSearch = (
    input: string,
    option: { value: string; label: React.ReactNode | undefined },
  ) =>
    option?.label?.toString().toLowerCase().includes(toLowerCase()) ||
    option?.value?.toString().toLowerCase().includes(toLowerCase());

  const SelectableChange = (value: {
    value: string;
    label: React.ReactNode;
  }) => {
    formik.setFieldValue(name, value);
  };

  const handleSelectChange = (value: any) => {
    formik.setFieldValue(name, value);
    if (onChange) onChange(value);
  };

  const handleSearchChange = (input: string) => {
    setSearchValue(input); // Update the search input value
  };

  return (
    <div className="ValidationField w-100">
      {no_label ? (
        <label htmlFor={name} className="text">
          <span>empty</span>
        </label>
      ) : label_icon ? (
        <div className="LabelWithIcon">
          <label htmlFor={name} className="text">
            {t(`${label ? label : name}`)}
          </label>
          <MdOutlineEdit size={22} style={{ color: "#A098AE" }} />
        </div>
      ) : (
        <label htmlFor={name} className="text">
          {t(`${label ? label : name}`)}
        </label>
      )}
      <Form.Item
        hasFeedback
        validateStatus={isError ? "error" : ""}
        help={isError ? errorMsg : ""}
      >
        <Select
          placeholder={t(
            `${placeholder ? placeholder : label ? label : name}`,
          )}
          disabled={isDisabled}
          options={translateOptions(option, t)}
          size="large"
          className={`${className} ${isError ? "Select_error" : ""} w-100`}
          value={formik.values[name]}
          allowClear
          {...(isMulti && { mode: "multiple" })}
          onChange={handleSelectChange}
          showSearch
          filterOption={handleSearch} // Custom filter function
          searchValue={searchValue} // Control the search input value
          onSearch={handleSearchChange} // Update search input value on change
        />
      </Form.Item>
    </div>
  );
};

export default React.memo(LocalSelectField);
