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, IDriver } from '@/shared/types/driver';
import { StyledMenuItem, StyledTextField } from '@/shared/theme/css';

const ALL_DRIVER_ID = '__all__';

const allDriversOption: IDriver = {
  id: ALL_DRIVER_ID,
  firstName: 'Tous',
  lastName: 'les chauffeurs',
  vehicle: '',
  fuelCard: [],
  fuelVolume: '',
  phone: '',
  email: '',
  departement: '',
  status: DriverRoadMapStatus.Disponible,
  permis: '',
  dateExpirationPermis: '',
  titreCarteSejour: '',
  cni: '',
};

interface Props {
  drivers: IDriver[];
  selectedDrivers: IDriver[];
  setSelectedDrivers: (drivers: IDriver[]) => 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.firstName?.toLowerCase().trim()}|${driver.lastName?.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: IDriver[]) => {
    const hasSelectedAll = value.some((v) => v.id === ALL_DRIVER_ID);
    if (hasSelectedAll) {
      if (isAllSelected) {
        setSelectedDrivers([]);
      } else {
        setSelectedDrivers(uniqueDrivers);
      }
    } else {
      setSelectedDrivers(value);
    }
  };

  const filterOptions = (options: IDriver[], { inputValue }: { inputValue: string }) => {
    const input = inputValue.toLowerCase().trim();
    return options.filter((option) => {
      if (option.id === ALL_DRIVER_ID) return 'tous les chauffeurs'.includes(input);
      const fullName = `${option.firstName ?? ''} ${option.lastName ?? ''}`.toLowerCase();
      return fullName.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.firstName ?? ''} ${option.lastName ?? ''}`.trim()
      }
      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.firstName} ${option.lastName}`,
            }}
          />
          <Typography
            sx={{
              color: option.id === ALL_DRIVER_ID ? 'text.secondary' : 'text.primary',
            }}
          >
            {option.id === ALL_DRIVER_ID
              ? 'Tous les chauffeurs'
              : `${option.firstName ?? ''} ${option.lastName ?? ''}`}
          </Typography>
        </StyledMenuItem>
      )}
      renderInput={(params) => (
        <StyledTextField 
          {...params} 
          label={selectedDrivers.length === 0 ? "Chauffeurs" : ""} 
          required 
           InputLabelProps={{
              shrink: true,
            }}
          placeholder="Sélectionner un chauffeur" 
        />
      )}
    />
  );
};

export default DriverSelector;
