import { useState } from 'react';

import Stack from '@material-hu/mui/Stack';
import { SxProps } from '@material-hu/mui/styles';

import Button from '@material-hu/components/design-system/Buttons/Button';
import HuCheckbox from '@material-hu/components/design-system/Checkbox/Checkbox';
import HuDropdown from '@material-hu/components/design-system/Dropdown';

import { useLokaliseTranslation } from 'src/utils/i18n';

type FilterOption<T> = {
  value: T;
  label: string;
};

type Props<T> = {
  applyFilters: (filters: T[]) => void;
  state: T[];
  dropdownLabel: string;
  options: FilterOption<T>[];
  contextTranslationKey?: string;
  sx?: SxProps;
};

const DropdownFilter = <T extends string>(props: Props<T>) => {
  const { applyFilters, dropdownLabel, state, options, sx } = props;
  const [open, setOpen] = useState(false);
  const [selectedFilters, setSelectedFilters] = useState<T[]>(state);
  const { t } = useLokaliseTranslation('time_tracker');

  const handleSelection = (option: FilterOption<T>) => {
    setSelectedFilters(prevFilters =>
      prevFilters.includes(option.value)
        ? prevFilters.filter(i => i !== option.value)
        : [...prevFilters, option.value],
    );
  };

  const handleDelete = () => {
    setSelectedFilters([]);
  };

  return (
    <HuDropdown
      label={`${dropdownLabel}${state.length > 0 ? ` (${state.length})` : ''}`}
      onClose={() => {
        setOpen(false);
      }}
      onClick={() => {
        setSelectedFilters(state);
        setOpen(true);
      }}
      open={open}
      sx={sx}
    >
      <Stack sx={{ p: 2, gap: 2, width: 312 }}>
        {options.map(option => (
          <HuCheckbox
            key={option.value}
            label={t(option.label)}
            checked={selectedFilters.includes(option.value)}
            onChange={() => {
              handleSelection(option);
            }}
          />
        ))}
      </Stack>
      <Stack
        sx={{
          borderTop: ({ palette }) =>
            `1px solid ${palette.new.border.neutral.default}`,
          flexDirection: 'row',
          gap: 2,
          p: 2,
        }}
      >
        <Button
          variant="tertiary"
          onClick={() => {
            handleDelete();
          }}
          fullWidth
        >
          {t('DELETE')}
        </Button>
        <Button
          variant="primary"
          onClick={() => {
            applyFilters(selectedFilters);
            setOpen(false);
          }}
          fullWidth
        >
          {t('APPLY')}
        </Button>
      </Stack>
    </HuDropdown>
  );
};

export default DropdownFilter;
