import React, { useMemo } from 'react';

import { useTranslations } from 'next-intl';
import { useSearchParams } from 'next/navigation';

import Highlight from '@/components/Highlight';
import { extractYouTubeId } from '@/components/YoutubeVideo';
import { useVideoPlayer } from '@/components/common/VideoModalPlayer';
import { cn } from '@/lib/utils';
import {
  getCreationCreators,
  getCreationDateLabel,
  getCreationHref,
} from '@/utils/creationHelpers';
import { getSearchUrl } from '@/utils/generalUtils';

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

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

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

const CreationVideoCard: React.FC<CreationVideoCardProps> = ({
  data,
  vertical,
  showCreatorProfession,
}) => {
  const { openVideo } = useVideoPlayer();
  const t = useTranslations('accessibility');

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

  const firstVideo = data.hivatkozasLista?.[0];
  const creators = getCreationCreators(data);
  const creatorsTooltip = creators.map((creator) => creator.megjelenitendoNev).join(', ');

  const isPublic = firstVideo?.status === 'public';

  if (!isPublic) {
    return null;
  }

  const videoId = firstVideo?.hivatkozas ?? '';
  const ytId = extractYouTubeId(videoId);
  const thumbnailSrc = ytId ? `https://i.ytimg.com/vi/${ytId}/hqdefault.jpg` : null;
  // Accessible name for the video — the creation name is used as the title.
  const videoTitle = data.nev?.trim() || t('video');

  return (
    <div className={cn('flex flex-col justify-start overflow-hidden ', vertical ? '' : 'flex-1')}>
      {videoId.length > 0 && (
        <>
          <button
            type="button"
            onClick={() => openVideo({ videoId, title: videoTitle })}
            aria-label={t('playVideo', { title: videoTitle })}
            className="group relative aspect-video w-full overflow-hidden bg-image-load focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mma-yellow"
          >
            {thumbnailSrc && (
              // eslint-disable-next-line @next/next/no-img-element
              <img
                src={thumbnailSrc}
                alt={videoTitle}
                className="h-full w-full object-cover transition duration-500 group-hover:scale-[1.03]"
              />
            )}
            <span className="absolute inset-0 flex items-center justify-center bg-black/0 transition-colors group-hover:bg-black/20">
              <svg
                viewBox="0 0 68 48"
                className="h-[34px] w-[48px] drop-shadow transition-transform group-hover:scale-110"
                aria-hidden="true"
              >
                <path
                  className="fill-[#212121]/80 transition-colors group-hover:fill-[#f00]"
                  d="M66.52,7.74c-0.78-2.93-2.49-5.41-5.42-6.19C55.79,0.13,34,0,34,0S12.21,0.13,6.9,1.55 C3.97,2.33,2.27,4.81,1.48,7.74C0.06,13.05,0,24,0,24s0.06,10.95,1.48,16.26c0.78,2.93,2.49,5.41,5.42,6.19 C12.21,47.87,34,48,34,48s21.79-0.13,27.1-1.55c2.93-0.78,4.64-3.26,5.42-6.19C67.94,34.95,68,24,68,24S67.94,13.05,66.52,7.74z"
                />
                <path className="fill-white" d="M 45,24 27,14 27,34" />
              </svg>
            </span>
          </button>
        </>
      )}

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

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

interface GenericCellContentProps {
  data: CreationListItem;
}

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

  return (
    <>
      {getCreationDateLabel(props.data) && (
        <div className="ui-meta line-clamp-1 text-[11px] leading-[1.05] sm:text-xs">
          {getCreationDateLabel(props.data)}
        </div>
      )}

      {props.data.nev && (
        <div className="line-clamp-2 w-full text-[12px] leading-[1.2] text-[#151720] sm:text-[13px]">
          <span className="group-hover/title:underline">
            {hasQuery ? (
              <Highlight text={props.data.nev} query={queries} />
            ) : (
              <span>{props.data.nev}</span>
            )}
          </span>
        </div>
      )}
    </>
  );
}

export default CreationVideoCard;
