import { FC, useState, useEffect } from "react";
import { Select as InternalSelect, MenuItem } from "@mui/material";

export type SelectOption = {
  value: string;
  label: string;
};

type SelectProps = {
  name: string;
  label: string;
  formState: Record<string, any>;
  required?: boolean;
  getOptions?: (formState: any) => Promise<SelectOption[]>;
  updateFormState?: (field: string, value: any) => void;
};

export const Select: FC<SelectProps> = ({
  name,
  label,
  formState,
  required = false,
  getOptions,
  updateFormState,
}) => {
  const [options, setOptions] = useState([] as SelectOption[]);

  useEffect(() => {
    const fetchData = async () => {
      if (getOptions) {
        const opts = await getOptions(formState);
        setOptions(opts);
      }
    };
    fetchData();
  }, [getOptions, formState]);

  return (
    <InternalSelect
      fullWidth
      name={name}
      label={label}
      variant="outlined"
      required={required}
      size="small"
      inputProps={{ id: name }}
      value={formState.values[name] || ""}
      onChange={(e: any) => updateFormState?.(name, e.target.value)}
      sx={{
        backgroundColor: "#fff",
      }}
    >
      {options.map((option: SelectOption) => (
        <MenuItem key={option.value} value={option.value}>
          {option.label}
        </MenuItem>
      ))}
    </InternalSelect>
  );
};
