import { type FC } from 'react';
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 { useTheme } from '@material-hu/mui/styles';

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

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

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

type ResultRowProps = {
  result: SearchResult;
  onSelect?: () => void;
};

const ResultRow: FC<ResultRowProps> = ({ result, onSelect }) => {
  const theme = useTheme();
  const navigate = useNavigate();

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

  return (
    <ButtonBase
      onMouseDown={event => {
        // Navigate on mousedown so a single press triggers the redirect
        // before focus shifts away from the input.
        event.preventDefault();
        handleNavigate();
      }}
      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();
        }
      }}
      sx={{
        display: 'block',
        width: '100%',
        textAlign: 'left',
        '&:hover': {
          backgroundColor: theme.palette.new.background.elements.grey,
        },
      }}
    >
      <HuListItem
        avatar={{ Icon: MODULE_ICON[result.module] }}
        text={{
          title: result.title ?? result.excerpt ?? '',
          withEllipsis: true,
        }}
      />
    </ButtonBase>
  );
};

export default ResultRow;
