/** biome-ignore-all lint/security/noDangerouslySetInnerHtml: <Text from backend> */
import { useNavigate } from 'react-router-dom';

import { IconChevronRight } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import Breadcrumbs from '@material-hu/components/design-system/Breadcrumbs';
import { type BreadcrumbLink } from '@material-hu/components/design-system/Breadcrumbs/types';
import CardContainer from '@material-hu/components/design-system/CardContainer';
import ListItem from '@material-hu/components/design-system/List/components/ListItem';
import { type ListItemAvatarProps } from '@material-hu/components/design-system/List/components/ListItem/types';
import Skeleton from '@material-hu/components/design-system/Skeleton';

import { useSidebarSearchQuery } from 'src/pages/dashboard/HuLibraries/hooks/useSidebarSearchQuery';
import { librariesRoutes } from 'src/pages/dashboard/HuLibraries/routes';
import {
  type ArticleSearchListItem,
  ArticleStatus,
  type LibraryNavigationState,
} from 'src/pages/dashboard/HuLibraries/types';
import { IconType } from 'src/types/icons';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { useLibrariesTitle } from '../../../hooks/useLibrariesTitle';

export type SearchItemProps = {
  article?: ArticleSearchListItem;
  loading?: boolean;
};

export const SearchItem = ({ article, loading = false }: SearchItemProps) => {
  const { t } = useLokaliseTranslation('general');
  const { search } = useSidebarSearchQuery();
  const navigate = useNavigate();
  const { palette } = useTheme();
  const librariesTitle = useLibrariesTitle();

  const navigateWithSearch = (to: string) =>
    navigate(to, { state: { search } satisfies LibraryNavigationState });

  const handleSelect = (selectedArticle: ArticleSearchListItem) => {
    if (!selectedArticle) return;

    const rootId = !selectedArticle.parentTree.length
      ? selectedArticle.id
      : selectedArticle.parentTree[0].id;
    const childId = !selectedArticle.parentTree.length
      ? undefined
      : selectedArticle.id;

    if (!rootId) return;

    navigateWithSearch(librariesRoutes.article(rootId, childId));
  };

  const getBreadcrumbItems = (): BreadcrumbLink[] => {
    if (!article || !article.parentTree.length) return [];

    const rootId = article.parentTree[0].id;
    if (!rootId) return [];

    return [
      {
        title: librariesTitle,
        onClick: () => navigate(librariesRoutes.base()),
      },
      ...article.parentTree.map(({ title, id }) => ({
        title,
        onClick: id
          ? () => navigateWithSearch(librariesRoutes.article(rootId, id))
          : undefined,
      })),
      {
        title: article.title,
        onClick: () =>
          navigateWithSearch(librariesRoutes.article(rootId, article.id)),
      },
    ];
  };

  const getAvatarProps = (): ListItemAvatarProps => {
    if (!article) return {};

    const isImageType = article.icon.type === IconType.IMAGE;
    const isEmojiType = article.icon.type === IconType.EMOJI;
    const isActiveArticle = article.status === ArticleStatus.ENABLED;

    return {
      src: isImageType ? article.icon.value : undefined,
      text: isEmojiType ? article.icon.value : undefined,
      withBadge: true,
      badgeProps: {
        color: isActiveArticle ? 'success' : 'disabled',
      },
    };
  };

  return (
    <CardContainer
      fullWidth
      padding={24}
      sx={{
        '& .back-highlights': {
          backgroundColor: palette.new.border.neutral.brand,
        },
      }}
    >
      <Stack sx={{ p: 0, gap: 3 }}>
        {loading && (
          <>
            <ListItem loading />
            <Skeleton
              width="100%"
              height={44}
            />
          </>
        )}
        {!loading && article && (
          <>
            <Stack>
              <ListItem
                avatar={getAvatarProps()}
                text={{
                  title: (
                    <div
                      dangerouslySetInnerHTML={{
                        __html: article.highlights.title[0] || article.title,
                      }}
                    />
                  ),
                }}
                action={{
                  onClick: () => handleSelect(article),
                  'aria-label': `${t('general:select')} ${article.title}`,
                  Icon: IconChevronRight,
                }}
                sx={{
                  '& .MuiListItem-root': { p: 0 },
                  '& .MuiAvatar-root': {
                    '& .MuiAvatar-img': { p: 1 },
                    '& .MuiTypography-root': {
                      fontSize: '20px',
                    },
                  },
                }}
              />
              <Stack sx={{ ml: 6 }}>
                <Breadcrumbs links={getBreadcrumbItems()} />
              </Stack>
            </Stack>
            {article.textContent && (
              <Typography
                variant="globalS"
                sx={{
                  display: '-webkit-box',
                  WebkitLineClamp: 2,
                  WebkitBoxOrient: 'vertical',
                  maxHeight: '44px',
                  overflow: 'hidden',
                  whiteSpace: 'normal',
                  overflowWrap: 'break-word',
                }}
                dangerouslySetInnerHTML={{
                  __html:
                    article.highlights.textContent[0] || article.textContent,
                }}
              />
            )}
          </>
        )}
      </Stack>
    </CardContainer>
  );
};
