/* eslint-disable @next/next/no-img-element */
import React, { useMemo } from 'react';

import { useSearchParams } from 'next/navigation';

import { FaYoutube } from 'react-icons/fa';

import Highlight from '@/components/Highlight';
import YouTubeVideo from '@/components/YoutubeVideo';
import { useIsVideoRoute } from '@/hooks/useIsVideoRoute';
import { cn } from '@/lib/utils';
import {
  getCreationCardImageSrc,
  getCreationCardVideoId,
  getCreationDateLabel,
  getCreationHref,
  isNonChronologicalData,
} from '@/utils/creationHelpers';
import { getSearchUrl } from '@/utils/generalUtils';
import { CREATION_CARD_BG_GRADIENTS } from '@/utils/ui';

import { CreationListItem } from '@/types/Creation';

import { Link, useRouter } from '@/i18n/navigation';

import CreationVideoCard from './CreationVideoCard';

interface CreationCardProps {
  data: CreationListItem;
  vertical?: boolean;
  type?: 'creation' | 'life' | 'news';
  rowContainsImage?: boolean; // temp function duplication in row component
  isVideoCard?: boolean;
  showCreatorProfession?: boolean;
  lifeTitleLines?: number;
}

function getLifeTitleLines(lines?: number) {
  if (typeof lines !== 'number' || !Number.isFinite(lines)) return 2;
  return Math.max(1, Math.floor(lines));
}

const CreationCard: React.FC<CreationCardProps> = (props) => {
  const router = useRouter();
  const isVideoRoute = useIsVideoRoute();
  const lifeTitleLines = getLifeTitleLines(props.lifeTitleLines);
  if (isVideoRoute) {
    return (
      <CreationVideoCard
        data={props.data}
        vertical={props.vertical}
        showCreatorProfession={props.showCreatorProfession}
      />
    );
  }

  // "random" color
  const colorIndex = props.data.alkotasAzonosito
    ? parseInt(props.data.alkotasAzonosito, 36) % CREATION_CARD_BG_GRADIENTS.length
    : (props.data.nev
        ? Array.from(props.data.nev).reduce((acc, c) => acc + c.charCodeAt(0), 0)
        : 0) % CREATION_CARD_BG_GRADIENTS.length;

  const descriptionHeight =
    props.data.cardType === 'creation'
      ? 'h-[74px] sm:h-[88px]'
      : props.data.cardType === 'news'
        ? 'h-[44px] sm:h-[52px]'
        : undefined;

  const hasImageOrVideo =
    getCreationCardVideoId(props.data) || getCreationCardImageSrc(props.data) ? true : false;
  const cardHref = getCreationHref(props.data);
  const hasCardHref =
    typeof cardHref === 'object' || (typeof cardHref === 'string' && cardHref.length > 0);

  const openCard = () => {
    if (!hasCardHref) return;

    if (typeof cardHref === 'string') {
      if (props.data.cardType === 'news') {
        window.open(cardHref, '_blank', 'noopener,noreferrer');
      } else {
        window.location.assign(cardHref);
      }
      return;
    }

    router.push(cardHref as never);
  };

  const handleCardClick = (event: React.MouseEvent<HTMLDivElement>) => {
    if (!hasCardHref) return;
    const target = event.target as HTMLElement;
    if (target.closest("a,button,input,select,textarea,label,[role='button']")) return;
    openCard();
  };

  const handleCardKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
    if (!hasCardHref) return;
    if (event.key !== 'Enter' && event.key !== ' ') return;
    event.preventDefault();
    openCard();
  };

  return (
    <div
      className={cn(
        'ui-card group relative flex h-full flex-col justify-start overflow-hidden rounded-[2px] !border-0 !bg-transparent !shadow-none transition-all duration-300 ease-out',
        props.vertical ? 'w-full' : 'min-w-0 flex-1',
        hasCardHref &&
          'cursor-pointer hover:!bg-[linear-gradient(180deg,rgba(255,255,255,0.995)_0%,rgba(253,254,255,0.985)_58%,rgba(248,251,254,0.95)_82%,rgba(238,245,252,0.54)_100%)] hover:!shadow-[0_22px_46px_-40px_rgba(20,25,40,0.28)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#9fb0bf]/30'
      )}
      onClick={handleCardClick}
      onKeyDown={handleCardKeyDown}
      role={hasCardHref ? 'link' : undefined}
      tabIndex={hasCardHref ? 0 : undefined}
    >
      {hasImageOrVideo && (
        <div
          className={cn(
            'relative w-full overflow-hidden bg-image-load',
            props.data.cardType === 'life' && 'aspect-square shrink-0'
          )}
        >
          {getCreationCardVideoId(props.data) && (
            <div className="relative aspect-square w-full overflow-hidden">
              <YouTubeVideo
                id={getCreationCardVideoId(props.data)}
                title={props.data.nev || 'youtube video'}
              />
            </div>
          )}

          {!getCreationCardVideoId(props.data) && getCreationCardImageSrc(props.data) && (
            <Link
              href={getCreationHref(props.data) as never}
              target={props.data.cardType === 'news' ? '_blank' : '_self'}
              rel="noreferrer"
              className="flex aspect-square min-h-full min-w-full items-center justify-center overflow-hidden"
            >
              <img
                src={getCreationCardImageSrc(props.data) || ''}
                alt={props.data.nev || ''}
                className="h-full w-full object-cover transition duration-500 group-hover:scale-[1.03] group-hover:brightness-[1.1]"
              />
            </Link>
          )}
          <div className="pointer-events-none absolute inset-0 bg-[linear-gradient(180deg,rgba(255,255,255,0)_0%,rgba(255,255,255,0)_62%,rgba(241,248,254,0.1)_84%,rgba(229,240,250,0.2)_100%)] opacity-0 transition-opacity duration-300 group-hover:opacity-100" />
        </div>
      )}

      {!hasImageOrVideo && props.data.cardType !== 'life' && (
        <Link
          className={cn(
            'w-full flex items-end aspect-square',
            props.data.id ? '' : 'pointer-events-none'
          )}
          href={getCreationHref(props.data) as never}
        >
          <div className="relative flex h-full w-full items-end overflow-hidden">
            <div
              className="absolute inset-0"
              style={{
                background: CREATION_CARD_BG_GRADIENTS[colorIndex],
                opacity: 1,
              }}
            />
            {props.data.nev && (
              <div
                className="absolute inset-0 flex items-center justify-center px-2"
                style={{ pointerEvents: 'none' }}
              >
                <span
                  className="line-clamp-3 select-none text-center text-xs font-semibold text-[#151720]/65 sm:text-sm"
                  style={{
                    textShadow: '0 1px 4px rgba(255,255,255,0.7)',
                    opacity: 0.85,
                    lineHeight: 1.2,
                    fontFamily: 'Roboto',
                  }}
                  dangerouslySetInnerHTML={{
                    __html: props.data.nev
                      .replaceAll('|', ', ')
                      .replaceAll(' ,', ',')
                      .replaceAll('&nbsp;', ' ')
                      .replaceAll('<0xa0>', ' '),
                  }}
                />
              </div>
            )}
          </div>
        </Link>
      )}

      {!hasImageOrVideo && props.data.cardType === 'life' && (
        <Link
          className={cn(
            'w-full flex items-end',
            props.rowContainsImage ? 'aspect-square' : '',
            props.data.id ? '' : 'pointer-events-none'
          )}
          href={getCreationHref(props.data) as never}
        >
          <div className="h-1 w-[50%] aspect-square bg-mma-cyan" />
        </Link>
      )}

      {props.data.cardType !== 'news' && (
        <div
          className={cn(
            'mt-1 flex h-full w-full flex-col gap-0.5 overflow-hidden',
            descriptionHeight
          )}
        >
          <Link
            className={cn(
              'flex min-w-0 flex-col gap-0.5',
              props.data.id ? '' : 'pointer-events-none'
            )}
            href={getCreationHref(props.data) as never}
          >
            <GenericCellContent data={props.data} lifeTitleLines={lifeTitleLines} />
          </Link>

          {props.data.cardType !== 'life' && (
            <div className="flex min-w-0 flex-col gap-0.5">
              {props.data.alkotoAzonosito && (
                <Link
                  href={{
                    pathname: '/alkoto/[id]',
                    params: { id: props.data.alkotoAzonosito },
                  }}
                  className="line-clamp-1 text-[11px] font-semibold uppercase tracking-[0.07em] leading-[1.15] text-[#151720]/90 hover:underline sm:text-xs"
                >
                  {props.data.megjelenitendoNev}
                  {props.showCreatorProfession && props.data.szakma ? (
                    <span className="normal-case font-medium tracking-normal text-[#151720]/60">
                      {' '}
                      {props.data.szakma}
                    </span>
                  ) : null}
                </Link>
              )}
              {props.data.telepules && (
                <Link
                  href={
                    (getSearchUrl(
                      props.data.telepules,
                      'alkotas',
                      null,
                      props.data.telepules,
                      'telepules'
                    ) || '') as never
                  }
                >
                  <div className="line-clamp-1 text-[11px] leading-[1.15] text-[#151720]/60 hover:underline sm:text-xs">
                    {props.data.telepules}
                  </div>
                </Link>
              )}
            </div>
          )}
        </div>
      )}

      {props.data.cardType === 'news' && (
        <div
          className={cn(
            'mt-1 flex h-full w-full flex-col gap-0.5 overflow-hidden',
            descriptionHeight
          )}
        >
          <a
            href={props.data.hivatkozas || ''}
            target="_blank"
            rel="noreferrer"
            className={'flex flex-col gap-0.5'}
          >
            <GenericCellContent data={props.data} lifeTitleLines={lifeTitleLines} />
          </a>
        </div>
      )}
    </div>
  );
};

interface GenericCellContentProps {
  data: CreationListItem;
  lifeTitleLines: number;
}

function GenericCellContent(props: GenericCellContentProps) {
  const getFormatedSubDate = (item: CreationListItem) => {
    let date = '';

    if (item.cim && item.cim.city) {
      if (date === '') date = item.cim.city;
      else date += ', ' + item.cim.city;
    }

    return date;
  };

  const isLife = props.data.cardType === 'life';
  const isLifeOrNews = isLife || props.data.cardType === 'news';
  const lifeTitleClampStyle: React.CSSProperties | undefined = isLife
    ? {
        display: '-webkit-box',
        WebkitBoxOrient: 'vertical',
        WebkitLineClamp: props.lifeTitleLines,
        overflow: 'hidden',
      }
    : undefined;

  const searchParams = useSearchParams();
  const kifejezes = (searchParams.get('kifejezes') || '').trim();
  const queries = useMemo(
    () => (kifejezes ? kifejezes.split(/\s+/).filter(Boolean) : []),
    [kifejezes]
  );
  const hasQuery = queries.length > 0;

  const dateClass = isNonChronologicalData(props.data)
    ? 'text-[10px] sm:text-[10.5px]'
    : 'text-[11.5px] sm:text-[12.5px]';

  return (
    <>
      {isLifeOrNews && (
        <>
          <div className="flex w-full flex-col">
            {getCreationDateLabel(props.data) && (
              <div
                className={cn(
                  'ui-meta line-clamp-1 font-bold leading-[1.05] text-[#151720]/85',
                  dateClass
                )}
              >
                {getCreationDateLabel(props.data)}
              </div>
            )}
            {getFormatedSubDate(props.data) && (
              <div className="line-clamp-1 w-full text-[11px] leading-[1.15] text-[#151720]/60 sm:text-xs">
                {getFormatedSubDate(props.data)}
              </div>
            )}
          </div>
          {props.data.nev && (
            <div
              className={cn(
                isLife ? undefined : 'line-clamp-2',
                'w-full text-[12px] leading-[1.2] text-[#151720] sm:text-[13px]'
              )}
              style={lifeTitleClampStyle}
              dangerouslySetInnerHTML={{
                __html: props.data.nev
                  .replaceAll('|', ', ')
                  .replaceAll(' ,', ',')
                  .replaceAll('&nbsp;', ' ')
                  .replaceAll('<0xa0>', ' '),
              }}
            />
          )}
          {props.data.tipusLabel && (
            <div className="w-full text-[11px] text-[#151720]/60">{props.data.tipusLabel}</div>
          )}
        </>
      )}

      {!isLifeOrNews && (
        <>
          {getCreationDateLabel(props.data) && (
            <div
              className={cn(
                'ui-meta line-clamp-1 font-bold leading-[1.05] text-[#151720]/85',
                dateClass
              )}
            >
              {getCreationDateLabel(props.data)}
            </div>
          )}
          {props.data.nev && (
            <div className="line-clamp-2 w-full text-[12px] leading-[1.2] text-[#151720] sm:text-[13px]">
              {props.data.hivatkozasLista && (
                <span className="mr-1 inline-block translate-y-[1px] align-text-bottom">
                  <FaYoutube className="inline-block" size={14} color="#FF0033" title="youtube" />
                </span>
              )}

              {hasQuery ? (
                <Highlight text={props.data.nev} query={queries} />
              ) : (
                <span>{props.data.nev}</span>
              )}
            </div>
          )}
        </>
      )}
    </>
  );
}

export default CreationCard;
