import React, { useEffect, useState } from "react";
import {
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Chip,
  Box,
} from "@mui/material";

interface Option {
  value: number;
  label: string;
}

interface MultiSelectProps {
  label: string;
  options: Option[];
  selectedValues: number[];
  onChange: (values: number[]) => void;
  isReset?: boolean;
}

const MultiSelect: React.FC<MultiSelectProps> = ({
  label,
  options,
  selectedValues,
  onChange,
  isReset,
}) => {
  const [displayValues, setDisplayValues] = useState<number[]>(selectedValues);

  const handleChange = (event: React.ChangeEvent<{ value: unknown }>) => {
    const value = event.target.value as number[];
    console.log("[debug] value", value);

    // Update display values state
    setDisplayValues(value);
    // Update selected values in parent component
    onChange(value);
  };

  useEffect(() => {
    setDisplayValues([]);
  }, [isReset]);

  return (
    <FormControl fullWidth>
      <InputLabel>{label}</InputLabel>
      <Select
        multiple
        value={displayValues}
        onChange={handleChange as any}
        renderValue={(selected) => (
          <Box sx={{ display: "flex", flexWrap: "wrap" }}>
            {(selected as number[]).map((value) => (
              <Chip
                key={value}
                label={options.find((item) => item.value == value)?.label ?? ""}
                sx={{ margin: 0.5 }}
              />
            ))}
          </Box>
        )}
      >
        {options.map((option) => (
          <MenuItem key={option.value} value={option.value}>
            <input
              type="checkbox"
              checked={displayValues.indexOf(option.value) > -1}
              readOnly
            />
            {option.label}
          </MenuItem>
        ))}
      </Select>
    </FormControl>
  );
};

export default MultiSelect;
