import type { ReactNode } from "react";
import type { Control, FieldValues, Path } from "react-hook-form";
import { Controller } from "react-hook-form";
import { FiChevronDown } from "react-icons/fi";

interface SelectOption {
  label: string;
  value: string;
}

interface SelectProps<T extends FieldValues> {
  name: Path<T>;
  control: Control<T>;
  options: SelectOption[];
  label?: string;
  placeholder?: string;
  icon?: ReactNode;
  className?: string;
  error?: string;
  required?: boolean;
}

export default function Select<T extends FieldValues>({
  name,
  control,
  options,
  label,
  placeholder,
  icon,
  className = "",
  error,
  required = false,
}: SelectProps<T>) {
  return (
    <div className="flex flex-col gap-0.5 xl:gap-1">
      {label && (
        <label className="text-[13px] 2xl:text-sm font-medium text-heading">
          {label}
          {required && <span className="ml-1 text-danger">*</span>}
        </label>
      )}

      <Controller
        name={name}
        control={control}
        render={({ field }) => (
          <div className="relative">
            <select
              {...field}
              className={`
          h-10 2xl:h-12
          w-full
          rounded-md
          2xl:rounded-xl
          border
          ${error ? "border-red-400" : "border-[#E5DFFF]"}
          bg-white
          pl-4
          pr-12
          font-body
           text-sm 2xl:text-base
          text-heading
          outline-none
          transition-all
          focus:border-[#8B5CF6]
          focus:ring-2
          focus:ring-[#8B5CF6]/10
          appearance-none
          cursor-pointer
        `}
            >
              {placeholder && (
                <option value="" disabled>
                  {placeholder}
                </option>
              )}

              {options.map((opt) => (
                <option key={opt.value} value={opt.value}>
                  {opt.label}
                </option>
              ))}
            </select>

            <span className="pointer-events-none absolute right-4 top-1/2 -translate-y-1/2 text-[#8B5CF6]">
              <FiChevronDown size={18} />
            </span>
          </div>
        )}
      />

      {error && <span className="text-xs text-danger">{error}</span>}
    </div>
  );
}
