import { FormControl, InputLabel, MenuItem, Select, SelectChangeEvent } from '@mui/material';
import { useContext, useEffect, useState } from 'react';
import { UserCurrentCorporateContext } from '../../../contexts/UserCurrentCorporate';
import axios from '../../../utils/axios';

/* ---------------------------------- types --------------------------------- */
type CorporateDataProps = {
  id: number;
  name: string;
};
/* -------------------------------------------------------------------------- */

export default function CorporatePopover() {
  const { corporateValue, setCorporateValue } = useContext(UserCurrentCorporateContext);
  const [corporateData, setCorporateData] = useState([]);

  const handleCorporateChange = (event: SelectChangeEvent) => {
    setCorporateValue(event.target.value as string);
  };

  useEffect(() => {
    (async () => {
      // @ts-ignore
      const corporateManages = await axios.get(`/corporate-manage`);
      setCorporateData(corporateManages.data);
    })();
  }, []);

  return (
    <FormControl>
      <InputLabel id="simple-corporate-select-lable">Corporate</InputLabel>
      <Select
        labelId="simple-corporate-select-lable"
        id="corporate-select-lable"
        value={corporateValue}
        label="Corporate"
        defaultValue={corporateValue}
        onChange={handleCorporateChange}
      >
        {corporateData.map((row: CorporateDataProps, index) => (
          <MenuItem key={index} value={row.id}>
            {row.name}
          </MenuItem>
        ))}
      </Select>
    </FormControl>
  );
}
