/* eslint-disable @typescript-eslint/no-explicit-any */
// components/SelectField.tsx
import React from "react";
import { useField, useFormikContext } from "formik";
import Select from "react-select";

interface OptionType {
  id: string | number;
  label: string;
}

interface Props {
  label: string;
  name: string;
  placeholder?: string;
  options: OptionType[];
  disabled?: boolean;
  required?: boolean;
}

const SelectField: React.FC<Props> = ({ label, name, placeholder, options, disabled = false, required = false }) => {
  const [field, meta] = useField(name);
  const { setFieldValue, setFieldTouched } = useFormikContext();
  const isError = meta.touched && meta.error;

  const reactSelectOptions = options.map((opt) => ({
    value: opt.id,
    label: opt.label,
  }));

  const selectedOption = reactSelectOptions.find((opt) => opt.value == (field?.value || field)) || null;
  return (
    <div className="input-style input-style-always-active has-borders has-icon validate-field col-lg-3 col-md-6 col-12">
      <div className="position-relative input-icon-position">
        <i className="ri ri-arrow-down-s-line color-primary" />
        <Select
          options={reactSelectOptions}
          value={selectedOption}
          placeholder={placeholder || "Select an option"}
          onChange={(option: any) => setFieldValue(name, option?.value)}
          onBlur={() => setFieldTouched(name, true)}
          classNamePrefix="react-select"
          className={isError ? "is-invalid" : ""}
          isDisabled={disabled}
        />
      </div>
      <label className="color-theme opacity-80 text-uppercase font-700 font-10">
        {label}: {required ? (<b className="color-red">*</b>) : ''}
      </label>
      {isError && <div className="text-danger px-2 error-box">{meta.error}</div>}
    </div>
  );
};

export default SelectField;
