import { StyledTextField } from '@/shared/theme/css';
import CloseIcon from '@mui/icons-material/Close';
import { Autocomplete, Box, Checkbox, IconButton, Typography } from '@mui/material';
import { useState, useMemo, useEffect } from 'react';

const ALL_DEPT = 'ALL';

interface Props {
  departments: string[];
  selectedDepartments: string[];
  setSelectedDepartments: (departments: string[]) => void;
}

const DepartmentSelectorAutocomplete: React.FC<Props> = ({
  departments,
  selectedDepartments,
  setSelectedDepartments,
}) => {
  const [dropdownOpen, setDropdownOpen] = useState(false);

  const uniqueDepartments = useMemo(() => Array.from(new Set(departments)), [departments]);

  const isAllSelected =
    uniqueDepartments.length > 0 &&
    uniqueDepartments.every((dept) => selectedDepartments.includes(dept));

  const handleChange = (_: any, value: string[]) => {
    if (value.includes(ALL_DEPT)) {
      if (isAllSelected) {
        setSelectedDepartments([]);
      } else {
        setSelectedDepartments(uniqueDepartments);
      }
    } else {
      setSelectedDepartments(value);
    }
  };

  useEffect(() => {
    if (selectedDepartments.includes(ALL_DEPT) && !isAllSelected) {
      setSelectedDepartments(selectedDepartments.filter((d) => d !== ALL_DEPT));
    }
  }, [selectedDepartments, isAllSelected, setSelectedDepartments]);

  useEffect(() => {
    if (isAllSelected) {
      setSelectedDepartments(uniqueDepartments);
    }
  }, [uniqueDepartments]);

  return (
    <Autocomplete
      multiple
      open={dropdownOpen}
      onOpen={() => setDropdownOpen(true)}
      onClose={() => setDropdownOpen(false)}
      options={[ALL_DEPT, ...uniqueDepartments]}
      value={selectedDepartments}
      onChange={handleChange}
      disableCloseOnSelect
      getOptionLabel={(option) => {
        if (!option) return '';
        if (option === ALL_DEPT) return 'Tous les départements';
        return typeof option === 'string' ? option : String(option);
      }}
      isOptionEqualToValue={(option, value) => option === value}
      renderOption={(props, option, { selected }) => (
        <li {...props}>
          <Checkbox
            style={{ marginRight: 8 }}
            checked={option === ALL_DEPT ? isAllSelected : selected}
          />
          <Typography>{option === ALL_DEPT ? 'Tous les départements' : option}</Typography>
        </li>
      )}
      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={selectedDepartments.length === 0 ? 'Départements' : ''}
          placeholder="Sélectionner un ou plusieurs départements"
          InputLabelProps={{
            shrink: true,
          }}
        />
      )}
    />
  );
};

export default DepartmentSelectorAutocomplete;
