import { type FC, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';

import { IconArrowRight } from '@tabler/icons-react';
import Divider from '@material-hu/mui/Divider';
import Paper from '@material-hu/mui/Paper';
import Popper from '@material-hu/mui/Popper';
import Stack from '@material-hu/mui/Stack';

import HuButton from '@material-hu/components/design-system/Buttons/Button';
import HuChip from '@material-hu/components/design-system/Chip';

import {
  type PanelMode,
  type SearchFilter,
  type SearchResult,
} from '../../types';

import RecentSearches from './RecentSearches';
import ResultsContent from './ResultsContent';

const FILTER_ORDER: SearchFilter[] = ['all', 'person', 'post', 'group'];

const FILTER_LABEL_KEY: Record<SearchFilter, string> = {
  all: 'filters.all',
  person: 'filters.people',
  post: 'filters.posts',
  group: 'filters.groups',
};

type ResultsPanelProps = {
  anchorEl: HTMLElement | null;
  open: boolean;
  onClose: () => void;
  mode: PanelMode;
  results: SearchResult[];
  filter: SearchFilter;
  onFilterChange: (filter: SearchFilter) => void;
  onExploreMore: () => void;
  onResultClick: () => void;
  recentSearches: string[];
  onSelectRecent: (term: string) => void;
  onRemoveRecent: (term: string) => void;
  onClearRecents: () => void;
};

const ResultsPanel: FC<ResultsPanelProps> = ({
  anchorEl,
  open,
  onClose,
  mode,
  results,
  filter,
  onFilterChange,
  onExploreMore,
  onResultClick,
  recentSearches,
  onSelectRecent,
  onRemoveRecent,
  onClearRecents,
}) => {
  const { t } = useTranslation('global_search');
  const showChrome = mode === 'results';
  const paperRef = useRef<HTMLDivElement | null>(null);

  // Close on click outside both the anchor (input) and the paper.
  useEffect(() => {
    if (!open) {
      return;
    }

    const handleDocumentMouseDown = (event: MouseEvent) => {
      const target = event.target as Node;
      if (anchorEl?.contains(target) || paperRef.current?.contains(target)) {
        return;
      }
      onClose();
    };

    document.addEventListener('mousedown', handleDocumentMouseDown);
    return () =>
      document.removeEventListener('mousedown', handleDocumentMouseDown);
  }, [open, anchorEl, onClose]);

  return (
    <Popper
      open={open}
      anchorEl={anchorEl}
      placement="bottom-start"
      sx={{ zIndex: theme => theme.zIndex.modal }}
    >
      <Paper
        ref={paperRef}
        sx={{
          mt: 1,
          width: anchorEl?.clientWidth ?? 600,
          maxWidth: '90vw',
          maxHeight: '70vh',
          display: 'flex',
          flexDirection: 'column',
          overflow: 'hidden',
          borderRadius: theme => theme.shape.borderRadiusL,
        }}
      >
        {mode === 'recent' ? (
          <RecentSearches
            items={recentSearches}
            onSelect={onSelectRecent}
            onRemove={onRemoveRecent}
            onClear={onClearRecents}
          />
        ) : (
          <>
            {showChrome && (
              <>
                <Stack
                  direction="row"
                  sx={{ gap: 1, p: 2, flexWrap: 'wrap' }}
                >
                  {FILTER_ORDER.map(option => (
                    <HuChip
                      key={option}
                      label={t(FILTER_LABEL_KEY[option])}
                      isSelected={filter === option}
                      onClick={() => onFilterChange(option)}
                    />
                  ))}
                </Stack>
                <Divider />
              </>
            )}
            <Stack sx={{ flex: 1, overflowY: 'auto' }}>
              <ResultsContent
                mode={mode}
                results={results}
                onResultClick={onResultClick}
              />
            </Stack>
            {showChrome && (
              <>
                <Divider />
                <HuButton
                  variant="text"
                  endIcon={<IconArrowRight size={16} />}
                  onClick={onExploreMore}
                  sx={{
                    backgroundColor: theme =>
                      theme.palette.new.background.layout.default,
                    py: 3,
                    borderTopLeftRadius: 0,
                    borderTopRightRadius: 0,
                  }}
                >
                  {t('more_results')}
                </HuButton>
              </>
            )}
          </>
        )}
      </Paper>
    </Popper>
  );
};

export default ResultsPanel;
