﻿'use client';

import React, { useState } from 'react';

import { useTranslations } from 'next-intl';

import { HiArrowUpRight } from 'react-icons/hi2';
import { IoMdQuote } from 'react-icons/io';
import { RiCrossFill } from 'react-icons/ri';
import Lightbox from 'yet-another-react-lightbox';
import Captions from 'yet-another-react-lightbox/plugins/captions';
import 'yet-another-react-lightbox/plugins/captions.css';
import Counter from 'yet-another-react-lightbox/plugins/counter';
import 'yet-another-react-lightbox/plugins/counter.css';
import Zoom from 'yet-another-react-lightbox/plugins/zoom';
import 'yet-another-react-lightbox/styles.css';

import CreatorAvatar from '@/components/creators/CreatorAvatar';
import { cn } from '@/lib/utils';
import { getFullMembershipString } from '@/utils/creatorHelpers';
import { removeHtmlTags } from '@/utils/creatorHelpers';
import { getSearchUrl } from '@/utils/generalUtils';
import { buildImageMetaText } from '@/utils/images';

import { CreationGalleryImage } from '@/types/Creation';
import { CreatorData } from '@/types/Creator';

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

interface CreatorHeaderRowProps {
  creator: CreatorData;
  quote?: string | null;
}

const CreatorHeaderRow: React.FC<CreatorHeaderRowProps> = ({ creator, quote }) => {
  const router = useRouter();
  const t = useTranslations('imageMeta');
  const tCommon = useTranslations('common');
  const tHeader = useTranslations('creatorHeaderRow');
  const tCreatorGrid = useTranslations('creatorPage.grid');
  const tParallelParams = useTranslations('parallelPathsPage.urlParams');
  const leftParam = tParallelParams('left');
  const [isOpen, setIsOpen] = useState<boolean>(false);
  const {
    profilkep,
    nev,
    szuletesiHely,
    szuletesiIdo,
    elhalalozasHelye,
    elhalalozasIdeje,
    szakmaOndef,
    mmaTagsagLista,
    galeria,
    cimkeFelho,
    szakma,
  } = creator;
  const sortedTags = [...(cimkeFelho ?? [])].sort((a, b) => b.cnt - a.cnt);
  const cleanQuote = quote ? removeHtmlTags(quote) : '';
  const tagCounts = sortedTags.map((tag) => tag.cnt);
  const minTagCount = tagCounts.length > 0 ? Math.min(...tagCounts) : 0;
  const maxTagCount = tagCounts.length > 0 ? Math.max(...tagCounts) : 0;
  const getTagSizeClass = (count: number) => {
    if (maxTagCount <= minTagCount) return 'text-xs';
    const ratio = (count - minTagCount) / (maxTagCount - minTagCount);
    if (ratio < 0.2) return 'text-[10px]';
    if (ratio < 0.4) return 'text-xs';
    if (ratio < 0.6) return 'text-sm';
    if (ratio < 0.8) return 'text-base';
    return 'text-lg';
  };
  const handleTagClick = (id: number, name: string) => {
    const title = creator?.nev ? `${creator.nev} - ${name}` : name;
    router.push(getSearchUrl(null, 'alkotas', id, title, null, creator.alkotoAzonosito) as never);
  };

  const getBirthDeath = () => {
    const birthParts: string[] = [];
    if (szuletesiHely) birthParts.push(szuletesiHely);
    if (szuletesiIdo) birthParts.push(szuletesiIdo);

    const birth = birthParts.join(', ');

    const deathParts: string[] = [];
    if (elhalalozasHelye) deathParts.push(elhalalozasHelye);
    if (elhalalozasIdeje) deathParts.push(elhalalozasIdeje);

    const death = deathParts.join(', ');

    return birth + (death ? ' – ' + death : '');
  };

  const showCompareActions = (creator.contentCount ?? 0) > 1;
  const hasTags = showCompareActions && sortedTags.length > 0;
  const hasCreatorMap = Boolean(creator.hasCreationMapData);
  const hasActionLinks = showCompareActions || hasCreatorMap;

  return (
    <div className="grid grid-cols-1 gap-3 lg:gap-4 lg:grid-cols-[minmax(0,2.05fr)_minmax(0,2.95fr)] xl:grid-cols-[minmax(0,1.95fr)_minmax(0,3.05fr)] lg:items-start">
      <section className="min-w-0">
        <div className="flex min-w-0 items-start gap-3 sm:gap-4">
          <CreatorAvatar
            imageKey={profilkep?.key}
            name={nev}
            onClick={() => setIsOpen(true)}
            width={480}
            height={480}
            wrapperClassName={cn(
              '!w-[136px] sm:!w-[152px] lg:!w-[164px] xl:!w-[176px] 2xl:!w-[188px] !max-w-none rounded-full',
              !galeria && 'cursor-default'
            )}
            imageClassName="rounded-full"
          />

          <div className="min-w-0 self-start flex flex-1 flex-col gap-2 sm:gap-2.5">
            <div className="min-w-0 flex flex-col gap-1.5 text-xs sm:text-sm">
              <div>
                <Link
                  className="hover:underline transition-all duration-300"
                  href={{
                    pathname: '/alkoto/[id]',
                    params: { id: creator.alkotoAzonosito },
                  }}
                >
                  <h1 className="text-base sm:text-lg md:text-[19px] lg:text-[20px] xl:text-[21px] font-bold text-[#151720] leading-tight break-words uppercase tracking-[0.02em]">
                    {elhalalozasIdeje ? (
                      <RiCrossFill className="inline text-sm sm:text-base -mt-0.5 sm:-mt-1" />
                    ) : null}
                    {nev}
                  </h1>
                </Link>

                {szakmaOndef && (
                  <div
                    className="text-sm sm:text-[15px] md:text-base font-semibold leading-tight tracking-[0.01em] text-[#151720]/90 [&_p]:m-0 [&_p]:leading-tight"
                    dangerouslySetInnerHTML={{ __html: szakmaOndef }}
                  />
                )}

                {szakma && !szakmaOndef && (
                  <div
                    className="text-sm sm:text-[15px] md:text-base font-semibold leading-tight tracking-[0.01em] text-[#151720]/90 [&_p]:m-0 [&_p]:leading-tight"
                    dangerouslySetInnerHTML={{ __html: szakma }}
                  />
                )}

                {getBirthDeath() && (
                  <span className="text-[#151720]/85 leading-[1.3]">{getBirthDeath()}</span>
                )}
              </div>

              <div className="flex flex-col gap-0.5 text-[13px] leading-[1.3] text-[#151720]/85">
                {mmaTagsagLista && mmaTagsagLista.length > 0 && (
                  <span className="space-y-0.5">
                    {mmaTagsagLista.map((membership) => (
                      <div key={membership.nev} className="leading-[1.3]">
                        {getFullMembershipString(membership)}
                      </div>
                    ))}
                  </span>
                )}
              </div>
            </div>
          </div>
        </div>
      </section>

      <section className="min-w-0">
        <div className="grid min-w-0 grid-cols-1 gap-2 lg:grid-cols-[minmax(0,1.35fr)_minmax(0,1.35fr)_minmax(210px,1fr)] xl:grid-cols-[minmax(0,1.45fr)_minmax(0,1.45fr)_minmax(220px,1fr)] lg:h-[164px] xl:h-[176px] 2xl:h-[188px]">
          {cleanQuote && (
            <Link
              href={{
                pathname: '/alkoto/[id]/palyakep',
                params: { id: creator.alkotoAzonosito },
              }}
              className={cn(
                'relative block h-full overflow-hidden bg-mma-blue p-3 lg:p-3.5 text-white shadow-sm transition hover:scale-[0.985]',
                !hasTags && 'lg:col-span-2'
              )}
            >
              <IoMdQuote className="pointer-events-none absolute -left-0 -top-0 text-lg lg:text-[24px] text-white/30 rotate-180" />
              <IoMdQuote className="pointer-events-none absolute bottom-0 right-0 text-lg lg:text-[24px] text-white/20" />
              <div className="flex h-full min-h-0 flex-col">
                <div className="flex min-h-0 flex-1 items-center pt-1.5 lg:pt-2">
                  <blockquote className="text-[14px] sm:text-[15px] md:text-[16px] xl:text-[17px] 2xl:text-[18px] text-white leading-[1.28] italic line-clamp-3 sm:line-clamp-4 2xl:line-clamp-5">
                    {cleanQuote}
                  </blockquote>
                </div>
                <div className="flex items-end justify-between pt-0.5 lg:pt-1">
                  <span className="inline-flex items-center gap-2 text-[12px] font-bold text-white/90 uppercase">
                    {tCommon('readMore')}
                    <HiArrowUpRight className="text-sm" />
                  </span>
                  <span className="opacity-0">.</span>
                </div>
              </div>
            </Link>
          )}

          {hasTags && (
            <section className="relative hidden h-full overflow-hidden border-4 border-mma-cyan bg-mma-cyan px-3 py-2 shadow-sm lg:block">
              <div className="relative z-10 flex h-full flex-col">
                <div className="text-[12px] font-bold uppercase text-mma-blue">
                  {tHeader('tagsTitle')}
                </div>
                <div className="mt-2 flex flex-1 flex-wrap content-start gap-1.5 overflow-y-auto overflow-x-hidden pr-1">
                  {sortedTags.map((tag) => {
                    return (
                      <button
                        key={tag.metaId}
                        className="inline-flex min-w-0 max-w-full items-center gap-2 rounded-full bg-neutral-200 px-2.5 py-1 text-xs font-bold text-mma-blue transition hover:bg-mma-yellow"
                        onClick={() => handleTagClick(tag.metaId, tag.nev)}
                      >
                        <span
                          className={cn(
                            'lowercase font-semibold whitespace-normal break-words text-left',
                            getTagSizeClass(tag.cnt)
                          )}
                        >
                          {tag.nev}
                        </span>
                      </button>
                    );
                  })}
                </div>
              </div>
            </section>
          )}

          {hasActionLinks && (
            <section className={cn('relative h-full', !cleanQuote && !hasTags && 'lg:col-span-3')}>
              <div
                className={cn(
                  'grid h-full gap-2',
                  hasCreatorMap ? 'lg:grid-rows-3' : 'lg:grid-rows-2'
                )}
              >
                {showCompareActions && (
                  <Link
                    href={{
                      pathname: '/alkoto/[id]/muveszeti-halo',
                      params: { id: creator.alkotoAzonosito },
                    }}
                    className="relative hidden h-full items-center justify-center gap-2 bg-mma-yellow px-3 py-2 text-[12px] font-bold text-center text-mma-blue uppercase shadow-lg transition hover:scale-[0.985] lg:flex"
                  >
                    <span className="absolute -right-2 -top-2 rounded-full bg-gradient-to-r from-purple-700 to-pink-700 px-3 py-1 text-[11px] font-bold text-white shadow-sm">
                      {tCommon('new')}
                    </span>
                    <span>{tCreatorGrid('kapcsolodasok')}</span>
                  </Link>
                )}

                {hasCreatorMap && (
                  <Link
                    href={{
                      pathname: '/alkoto/[id]/terkep',
                      params: { id: creator.alkotoAzonosito },
                    }}
                    className="flex h-full items-center justify-center bg-mma-cyan px-3 py-2 text-[12px] font-bold text-center text-mma-blue uppercase shadow-lg transition hover:scale-[0.985]"
                  >
                    <span>{tCreatorGrid('terkep')}</span>
                  </Link>
                )}

                {showCompareActions && (
                  <Link
                    href={{
                      pathname: '/parhuzamos-eletutak',
                      query: { [leftParam]: creator.alkotoAzonosito },
                    }}
                    className="flex h-full items-center justify-center gap-2 bg-mma-blue px-3 py-2 text-[12px] font-bold text-center text-white uppercase shadow-lg transition hover:scale-[0.985]"
                  >
                    <span>{tCreatorGrid('parhuzamos-eletutak')}</span>
                    <HiArrowUpRight className="text-base xl:text-lg" />
                  </Link>
                )}
              </div>
            </section>
          )}
        </div>
      </section>

      {galeria && galeria.length > 0 && (
        <Lightbox
          open={isOpen}
          close={() => setIsOpen(false)}
          plugins={[Zoom, Captions, ...(galeria.length > 1 ? [Counter] : [])]}
          zoom={{ maxZoomPixelRatio: 3, scrollToZoom: true }}
          carousel={{
            padding: 60,
            finite: true,
            preload: 5,
          }}
          captions={{ showToggle: false, hidden: false }}
          render={{
            buttonPrev: galeria.length > 1 ? undefined : () => null,
            buttonNext: galeria.length > 1 ? undefined : () => null,
          }}
          slides={galeria.map((image: CreationGalleryImage) => ({
            src: `${process.env.NEXT_PUBLIC_API_URL}/imageRepository/getImage?key=${image.key}`,
            width: image.width,
            height: image.height,
            title: nev,
            description: buildImageMetaText(image, true, {
              source: t('source'),
              photo: t('portraitPhoto'),
              rightsHolder: t('rightsHolder'),
            }),
          }))}
        />
      )}
    </div>
  );
};

export default CreatorHeaderRow;
