import { type FC } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';

import {
  IconArticle,
  IconFileText,
  IconUser,
  IconUsers,
  type TablerIcon,
} from '@tabler/icons-react';
import ButtonBase from '@material-hu/mui/ButtonBase';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import HuList from '@material-hu/components/design-system/List';
import HuListItem from '@material-hu/components/design-system/List/components/ListItem';

import PlaceholderState from './PlaceholderState';
import {
  type ContentModule,
  type PanelMode,
  type SearchResult,
  type SearchResultType,
} from './types';

const MODULE_GROUP: Record<ContentModule, SearchResultType> = {
  USERS: 'person',
  GROUPS: 'group',
  FEED: 'post',
  GROUP_POSTS: 'post',
  ARTICLES: 'post',
};

const MODULE_ICON: Record<ContentModule, TablerIcon> = {
  USERS: IconUser,
  GROUPS: IconUsers,
  FEED: IconFileText,
  GROUP_POSTS: IconFileText,
  ARTICLES: IconArticle,
};

const RESULT_TYPES_ORDER: SearchResultType[] = ['person', 'post', 'group'];

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

type ResultsContentProps = {
  mode: PanelMode;
  results: SearchResult[];
  onResultClick: () => void;
};

const SKELETON_ROWS = 5;

const ResultsContent: FC<ResultsContentProps> = ({
  mode,
  results,
  onResultClick,
}) => {
  const { t } = useTranslation('global_search');
  const theme = useTheme();
  const navigate = useNavigate();

  const handleNavigate = (result: SearchResult) => {
    try {
      const { pathname, search, hash } = new URL(result.path);
      navigate(`${pathname}${search}${hash}`);
    } catch {
      navigate(result.path);
    }
    onResultClick();
  };

  if (mode === 'empty' || mode === 'no-results' || mode === 'error') {
    return <PlaceholderState variant={mode} />;
  }

  if (mode === 'loading') {
    return (
      <HuList>
        {Array.from({ length: SKELETON_ROWS }).map((_, index) => (
          <HuListItem
            key={index}
            loading
          />
        ))}
      </HuList>
    );
  }

  const grouped = RESULT_TYPES_ORDER.map(type => ({
    type,
    items: results.filter(result => MODULE_GROUP[result.module] === type),
  })).filter(entry => entry.items.length > 0);

  return (
    <Stack sx={{ gap: 1, py: 1 }}>
      {grouped.map(entry => (
        <Stack key={entry.type}>
          <Typography
            variant="globalXS"
            sx={{
              px: 2,
              py: 0.5,
              color: theme.palette.new.text.neutral.lighter,
            }}
          >
            {t(RESULT_TYPE_LABEL_KEY[entry.type])}
          </Typography>
          <HuList>
            {entry.items.map(item => (
              <ButtonBase
                key={item.id}
                onMouseDown={event => {
                  // Navigate on mousedown so a single press triggers the redirect
                  // before focus shifts away from the input.
                  event.preventDefault();
                  handleNavigate(item);
                }}
                onKeyDown={event => {
                  // ButtonBase fires onClick on Enter/Space; we don't bind
                  // onClick (to avoid double-fire after mousedown)
                  if (event.key === 'Enter' || event.key === ' ') {
                    event.preventDefault();
                    handleNavigate(item);
                  }
                }}
                sx={{
                  display: 'block',
                  width: '100%',
                  textAlign: 'left',
                  '&:hover': {
                    backgroundColor: theme.palette.new.background.elements.grey,
                  },
                }}
              >
                <HuListItem
                  avatar={{ Icon: MODULE_ICON[item.module] }}
                  text={{
                    title: item.title ?? item.excerpt ?? '',
                    withEllipsis: true,
                  }}
                />
              </ButtonBase>
            ))}
          </HuList>
        </Stack>
      ))}
    </Stack>
  );
};

export default ResultsContent;
