/** 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 { IconType } from '@material-hu/types/icons';

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 {
  type ArticleSearchListItem,
  ArticleStatus,
  type LibraryNavigationState,
} from 'src/pages/dashboard/HuLibraries/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { useSidebarSearchQuery } from '../../hooks/useSidebarSearchQuery';
import { huLibrariesRoutes } from '../../routes';

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 handleSelect = () => {
    if (!article) return;

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

    if (!rootId) return;

    const state: LibraryNavigationState = { search };
    navigate(huLibrariesRoutes.article(rootId, childId), { state });
  };

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

    const rootId = article.parentTree[0].id;
    const items = [
      ...article.parentTree,
      { id: article.id, title: article.title },
    ];

    return items.map(item => ({
      title: item.title,
      onClick: () => {
        if (!rootId) return;
        const state: LibraryNavigationState = { search };
        const childId = item.id === rootId ? undefined : (item.id ?? undefined);
        navigate(huLibrariesRoutes.article(rootId, childId), { state });
      },
    }));
  };

  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,
                  '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={getBreadcrumbLinks()} />
              </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>
  );
};
