import { useEffect, useState } from 'react';
import { Checkbox, ListItemText, MenuItem, Select } from '@mui/material';
import { ExpandMore } from '@mui/icons-material';
import { useStyles as tableStyles } from './styles/tableStyles';
import { CLINIC_STATUS } from '../constants';

function TableSelect({ name, header, getOptions, options, MenuProps }) {
  const tableClasses = tableStyles();
  const [optionsData, setOptionsData] = useState(options ?? []);
  const [selectedValues, setSelectedValues] = useState([]);

  const handleChange = (event) => {
    const value = event.target.value;
    let newSelectedValues;

    if (Array.isArray(value)) {
      newSelectedValues = value;
    } else {
      newSelectedValues = selectedValues.includes(value)
        ? selectedValues.filter((item) => item !== value)
        : [value];
    }

    setSelectedValues(newSelectedValues);

    header.column.setFilterValue(
      newSelectedValues.length > 0 ? newSelectedValues : undefined
    );
  };

  const getOptionsData = async () => {
    const resp = await getOptions();
    setOptionsData(resp?.data);
  };

  useEffect(() => {
    if (!options) getOptionsData();
  }, []);

  return (
    <>
      <Select
        className={tableClasses.selectFilter}
        fullWidth
        displayEmpty
        IconComponent={ExpandMore}
        onChange={handleChange}
        value={selectedValues}
        margin="none"
        MenuProps={MenuProps}
        renderValue={() => null}
      >
        {optionsData.map((data) => (
          <MenuItem key={data?.id} value={data?.name}>
            <Checkbox checked={selectedValues.indexOf(data.name) > -1} />
            <ListItemText
              className={tableClasses.ListItemTextClass}
              primary={
                data?.name ===
                CLINIC_STATUS.APPROVAL_PENDING_DOCUMENT_RESUBMITTED ? (
                  <div>
                    Approval Pending:
                    <div>Document resubmitted</div>
                  </div>
                ) : (
                  <div>
                    {data?.showName ||
                      data?.name?.replace('_', ' ').toLowerCase()}
                  </div>
                )
              }
            />
          </MenuItem>
        ))}
      </Select>
    </>
  );
}

export default TableSelect;
