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';
import { useNavigate } from 'react-router-dom';

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

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

  const navigate = useNavigate();
  const currentPathname = window.location.pathname;
  const desiredPart = currentPathname.split('/')[1];

  const handleCorporateChange = (event: SelectChangeEvent) => {
    setCorporateValue(event.target.value as string);
    if (desiredPart === 'user-profile') {
      navigate('/alarm-center');
    }
  };

  useEffect(() => {
    (async () => {
      try {
        const corporateManages = await axios.get(`/corporate-manage`, {
          signal: controller.signal,
        });
        setCorporateData(corporateManages.data);

        const storageCorporateValue = corporateManages.data.find(
          (item: { id: number }) => item.id === parseInt(corporateValue)
        );

        setCorporateValue(
          storageCorporateValue ? storageCorporateValue.id : corporateManages.data[0].id
        );
      } catch (error: any) {
        console.error('Error fetching data:', error.message);
      }

      return () => {
        controller.abort();
      };
    })();
  }, []);

  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>
  );
}
