import React, { useEffect, useMemo } from 'react';
import { Autocomplete, Checkbox, ListItem, Typography } from '@mui/material';
import CheckBoxIcon from '@mui/icons-material/CheckBox';
import CheckBoxOutlineBlankIcon from '@mui/icons-material/CheckBoxOutlineBlank';
import { DriverRoadMapStatus, IActiveDriver } from '@/shared/types/driver';
import { StyledMenuItem, StyledTextField } from '@/shared/theme/css';

const ALL_DRIVER_ID = -1;

const allDriversOption: IActiveDriver = {
  id: ALL_DRIVER_ID,
  name: 'Tous les chauffeurs',
  departmentId: 0,
};

interface Props {
  drivers: IActiveDriver[];
  selectedDrivers: IActiveDriver[];
  setSelectedDrivers: (drivers: IActiveDriver[]) => void;
}

const icon = <CheckBoxOutlineBlankIcon fontSize="small" />;
const checkedIcon = <CheckBoxIcon fontSize="small" />;

const DriverSelector: React.FC<Props> = ({ drivers, selectedDrivers, setSelectedDrivers }) => {
  const uniqueDrivers = useMemo(() => {
    const seen = new Set<string>();
    return drivers.filter((driver) => {
      const key = driver.name.toLowerCase().trim();
      if (seen.has(key)) return false;
      seen.add(key);
      return true;
    });
  }, [drivers]);

  const isAllSelected =
    uniqueDrivers.length > 0 &&
    uniqueDrivers.every((driver) => selectedDrivers.some((selected) => selected.id === driver.id));

  const handleChange = (_: any, value: IActiveDriver[]) => {
    const hasSelectedAll = value.some((v) => v.id === ALL_DRIVER_ID);
    if (hasSelectedAll) {
      if (isAllSelected) {
        setSelectedDrivers([]);
      } else {
        setSelectedDrivers(uniqueDrivers);
      }
    } else {
      setSelectedDrivers(value);
    }
  };

  const filterOptions = (options: IActiveDriver[], { inputValue }: { inputValue: string }) => {
    const input = inputValue.toLowerCase().trim();
    return options.filter((option) => {
      if (option.id === ALL_DRIVER_ID) return 'tous les chauffeurs'.includes(input);
      return option.name.toLowerCase().includes(input);
    });
  };

  useEffect(() => {
    if (selectedDrivers.some((driver) => driver.id === ALL_DRIVER_ID) && !isAllSelected) {
      setSelectedDrivers(selectedDrivers.filter((driver) => driver.id !== ALL_DRIVER_ID));
    }
  }, [selectedDrivers, isAllSelected, setSelectedDrivers]);

  useEffect(() => {
    if (isAllSelected) {
      setSelectedDrivers(uniqueDrivers);
    }
  }, [uniqueDrivers]);

  return (
    <Autocomplete
      multiple
      disableCloseOnSelect
      data-testid="driver-selector"
      options={[allDriversOption, ...uniqueDrivers]}
      value={selectedDrivers}
      onChange={handleChange}
      getOptionLabel={(option) =>
        option.id === ALL_DRIVER_ID ? 'Tous les chauffeurs' : option.name
      }
      isOptionEqualToValue={(option, value) => option.id === value.id}
      filterOptions={filterOptions}
      renderOption={(props, option, { selected }) => (
        <StyledMenuItem {...props}>
          <Checkbox
            size="small"
            checked={option.id === ALL_DRIVER_ID ? isAllSelected : selected}
            icon={icon}
            checkedIcon={checkedIcon}
            inputProps={{
              'aria-label': option.id === ALL_DRIVER_ID ? 'Tous les chauffeurs' : option.name,
            }}
          />
          <Typography
            sx={{
              color: option.id === ALL_DRIVER_ID ? 'text.secondary' : 'text.primary',
            }}
          >
            {option.name}
          </Typography>
        </StyledMenuItem>
      )}
      renderInput={(params) => (
        <StyledTextField
          {...params}
          label={selectedDrivers.length === 0 ? 'Chauffeurs' : ''}
          required
          InputLabelProps={{
            shrink: true,
          }}
          placeholder="Sélectionner un chauffeur"
        />
      )}
    />
  );
};

export default DriverSelector;
