import { useMemo, useState } from 'react';

import Typography from '@material-hu/mui/Typography';

import SelectableListItem from '@material-hu/components/composed-components/SelectableListItem';
import InputSearch from '@material-hu/components/design-system/Inputs/Search';
import List from '@material-hu/components/design-system/List';
import StateCard from '@material-hu/components/design-system/StateCard';
import Title from '@material-hu/components/design-system/Title';
import { Drawer, useDrawerLayer } from '@material-hu/components/layers/Drawers';

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

import { type ActiveCategory } from '../../types';

type KudosCategoriesDrawerProps = {
  hiddenCategories: ActiveCategory[];
  selectedCategoryId: number | null;
  onApply: (categoryId: number | null) => void;
};

export const KudosCategoriesDrawer = ({
  hiddenCategories,
  selectedCategoryId,
  onApply,
}: KudosCategoriesDrawerProps) => {
  const { closeDrawer } = useDrawerLayer();
  const [searchQuery, setSearchQuery] = useState('');

  const { t } = useLokaliseTranslation([
    'acknowledgements',
    'material_hu_only',
  ]);

  const filteredCategories = useMemo(() => {
    return hiddenCategories.filter(cat =>
      cat.name.toLowerCase().includes(searchQuery.toLowerCase()),
    );
  }, [hiddenCategories, searchQuery]);

  const initialDraftId = useMemo(() => {
    if (selectedCategoryId === null) return null;

    if (hiddenCategories.some(cat => cat.id === selectedCategoryId)) {
      return selectedCategoryId;
    }

    return null;
  }, [selectedCategoryId, hiddenCategories]);

  const [draftCategoryId, setDraftCategoryId] = useState<number | null>(
    () => initialDraftId,
  );

  const handleResetFilters = () => {
    setSearchQuery('');
    onApply(null);
    closeDrawer();
  };

  const handleApplyFilters = () => {
    onApply(draftCategoryId);
    closeDrawer();
  };

  return (
    <>
      <Drawer.Header
        title={t('general:filter')}
        onClose={closeDrawer}
      />
      <Drawer.Body slotProps={{ sx: { gap: 1 } }}>
        <Typography
          variant="globalS"
          fontWeight="fontWeightSemiBold"
        >
          {t('acknowledgement_categories')}
        </Typography>
        <InputSearch
          placeholder={t('general:search')}
          onChange={value => setSearchQuery(value)}
          value={searchQuery}
        />
        <List
          sx={{
            backgroundColor: ({ palette }) =>
              palette.new.background.elements.grey,
            border: 'none',
            borderRadius: 2,
            overflow: 'auto',
          }}
        >
          {!filteredCategories.length && searchQuery && (
            <StateCard
              title={t('material_hu_only:hu_inputs.no_results_found')}
              description={t('general:try_again_with_other_words')}
            />
          )}
          {filteredCategories.map(cat => (
            <SelectableListItem
              key={cat.id}
              variant="single"
              component="li"
              id={cat.id.toString()}
              sx={{ p: 2, borderRadius: 1 }}
              onSelect={() => setDraftCategoryId(cat.id)}
              selected={draftCategoryId === cat.id}
            >
              <Title
                variant="S"
                fontWeight="fontWeightRegular"
                title={cat.name}
                overflow="tooltip"
                withEllipsis
              />
            </SelectableListItem>
          ))}
        </List>
      </Drawer.Body>
      <Drawer.Actions
        primaryButtonProps={{
          fullWidth: true,
          children: t('general:apply'),
          onClick: handleApplyFilters,
          disabled: draftCategoryId === initialDraftId,
        }}
        secondaryButtonProps={{
          fullWidth: true,
          children: t('general:reset_filters'),
          onClick: handleResetFilters,
        }}
      />
    </>
  );
};
