import React, { useEffect, useMemo, useState } from 'react';
import { Autocomplete, Box, Checkbox, IconButton, 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';
import CloseIcon from '@mui/icons-material/Close';

const ALL_DRIVER_ID = -1;

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

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);
    });
  };
  const [dropdownOpen, setDropdownOpen] = useState(false);

  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"
      open={dropdownOpen}
      onOpen={() => setDropdownOpen(true)}
      onClose={() => setDropdownOpen(false)}
      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>
      )}
        PaperComponent={(props) => (
        <Box
          sx={{
            bgcolor: 'background.paper',
            borderRadius: 2, 
          }}
        >
          <Box sx={{ display: 'flex', justifyContent: 'flex-end', px: 1, pt: 1 }}>
            <IconButton size="small" onClick={() => setDropdownOpen(false)}>
              <CloseIcon fontSize="small" />
            </IconButton>
          </Box>
          {props.children}
        </Box>
      )}
      renderInput={(params) => (
        <StyledTextField
          {...params}
          label={selectedDrivers.length === 0 ? 'Chauffeurs' : ''}
          required
          InputLabelProps={{
            shrink: true,
          }}
          placeholder="Sélectionner un ou plusieurs chauffeur"
        />
      )}
    />
  );
};

export default DriverSelector;
