'use client';

import React, { useEffect, useRef, useState } from 'react';

import { useTranslations } from 'next-intl';

import { Images, MapPinned } from 'lucide-react';
import { IoArrowForward } from 'react-icons/io5';

import FeaturedCreationsBlock from '@/components/FeaturedCreationsBlock';
import Gallery from '@/components/Gallery';
import YouTubeVideo from '@/components/YoutubeVideo';
import CreationMap, { convertMapData } from '@/components/maps/CreationMap';
import TagRow from '@/components/tags/TagRow';
import { getMainImage, getPlaceOfOrigin } from '@/utils/creationHelpers';
import { getDataByAttributeName, getSearchUrl } from '@/utils/generalUtils';

import { CreationGalleryImage, CreationListItem, CreationPageItem } from '@/types/Creation';

import type { AppLocale } from '@/config/i18n';
import { Link } from '@/i18n/navigation';
import { useRouter } from '@/i18n/navigation';

interface CreationClientProps {
  creation: CreationPageItem;
  featuredCreations: CreationListItem[];
  locale: AppLocale;
}

const CreationClient: React.FC<CreationClientProps> = ({ creation, featuredCreations, locale }) => {
  const router = useRouter();
  const t = useTranslations('creationPage');
  // todo
  const handleTagListClick = (id: number, nev: string) => {
    router.push(getSearchUrl(null, 'alkotas', id, nev) as never);
  };

  const schemaCreation = {
    '@context': 'https://schema.org',
    '@type': 'CreativeWork',
    name: creation?.nev,
    creator: creation?.megjelenitendoNev,
    image: getMainImage(creation?.fokep?.key),
    description:
      creation?.megjelenitendoNev +
      ', ' +
      creation?.nev +
      getPlaceOfOrigin(creation?.keletkezesHelyeCity),
    url: `${process.env.NEXT_PUBLIC_BASE_URL}/alkotas/${creation?.alkotasAzonosito}`,
    inLanguage: 'hu',
    dateCreated: creation?.label,
    locationCreated: creation?.keletkezesHelyeCity,
  };

  const videos = creation.hivatkozasLista || [];
  const azopusVideos = videos?.filter((v) => v.tipus === 'alkotas_video');

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(schemaCreation) }}
      />

      {locale === 'en' && creation.nemForditottTartalom && (
        <p className="text-xs lg:text-md lg:text-base text-red-500 font-medium">
          {t('languageNote')}
        </p>
      )}

      <div className="w-full flex flex-col gap-4 md:gap-8 pb-page pt-page">
        {creation && (
          <>
            {creation.targyszo && creation.targyszo.filter((tag) => tag.nev).length > 0 && (
              <div className="flex justify-between items-center">
                <TagRow
                  tags={creation.targyszo
                    .filter((tag) => tag.nev)
                    .map((tag) => ({
                      key: tag.id.toString(),
                      label: tag.nev,
                      onClick: () => handleTagListClick(tag.id, tag.nev),
                    }))}
                  className="justify-end"
                />
              </div>
            )}

            {/* {locale === "en" &&
              creation.attributumok &&
              creation.attributumok.length > 0 && (
                <div className="flex justify-between items-center">
                  <TagRow
                    tags={getTagList(locale).map((tag) => ({
                      key: tag.id.toString(),
                      label: tag.nev,
                      onClick: () => handleTagListClick(tag.id, tag.nev),
                    }))}
                    className="justify-end"
                  />
                </div>
              )} */}

            <CreationHeader data={creation} locale={locale} />

            {azopusVideos.length > 0 && (
              <div className="w-full bg-white border-t border-b border-gray-200 py-12">
                <div className="w-full flex flex-col md:grid md:grid-cols-6 items-start gap-4 lg:gap-8">
                  {/* Left side - Video (3/6 columns) */}
                  <div className="w-full col-span-full md:col-span-3 order-1 md:order-1">
                    <div className="w-full aspect-video overflow-hidden shadow-lg bg-gray-100">
                      <YouTubeVideo
                        title={azopusVideos[0].cim}
                        id={azopusVideos[0].hivatkozas}
                        backgroundSize="cover"
                        poster="maxresdefault"
                      />
                    </div>
                  </div>

                  {/* Right side - Description and link (3/6 columns) */}
                  <div className="w-full col-span-full md:col-span-3 flex flex-col order-2 md:order-2 px-4 md:px-0 h-full justify-between gap-2 lg:py-4 xl:py-8 2xl:py-12">
                    <div className="flex flex-col gap-4 lg:gap-8">
                      <h3 className="text-mma-blue text-xl lg:text-2xl uppercase font-bold">
                        {t('howItWasMade.title')}
                      </h3>
                      <p className="text-gray-700 text-base lg:text-lg leading-relaxed">
                        {t('howItWasMade.subtitle')}
                        <br />
                        {t.rich('howItWasMade.description', {
                          artist: creation?.megjelenitendoNev || '',
                          profession: creation?.szakma || '',
                          title: creation.nev || '',
                          year: creation.label || '',
                          bold: (chunks) => <strong>{chunks}</strong>,
                        })}
                      </p>
                    </div>
                    <Link
                      href={{
                        pathname: '/alkoto/[id]/alkotas-videok',
                        params: {
                          id: creation?.alkotoAzonosito,
                        },
                      }}
                      className="inline-flex items-center gap-2 text-mma-blue text-base lg:text-lg xl:text-xl uppercase font-bold hover:text-mma-yellow transition-colors group"
                    >
                      <div className="flex items-center gap-2 underline">
                        <span>
                          {t('howItWasMade.moreVideos', {
                            artist: creation?.megjelenitendoNev || '',
                          })}
                        </span>
                        <IoArrowForward className="text-sm md:text-md" />
                      </div>
                    </Link>
                  </div>
                </div>
              </div>
            )}

            {creation?.alkotoAzonosito && (
              <FeaturedCreationsBlock
                creations={featuredCreations}
                creatorId={creation?.alkotoAzonosito ?? ''}
                leftTitle={t('featuredCreations')}
              />
            )}
          </>
        )}
      </div>
    </>
  );
};

interface CreationHeaderProps {
  data: CreationPageItem;
  locale: string;
}

type Mode = 'IMAGE' | 'MAP' | 'PLACEHOLDER' | null;

const CreationHeader: React.FC<CreationHeaderProps> = ({ data, locale }) => {
  const [mode, setMode] = useState<Mode>(null);
  const [isDescriptionExpanded, setIsDescriptionExpanded] = useState(false);
  const [descriptionClampHeight, setDescriptionClampHeight] = useState<number | null>(null);
  const [isDescriptionOverflowing, setIsDescriptionOverflowing] = useState(false);
  const descriptionContainerRef = useRef<HTMLDivElement>(null);
  const visualColumnRef = useRef<HTMLDivElement>(null);
  const t = useTranslations('creationPage');

  const videos = data.hivatkozasLista || [];
  const otherVideos = videos?.filter((v) => v.tipus === 'alkotasrol_szolo_video');
  const hasMap = !!data.keletkezesHelyeKoordinatak && data.keletkezesHelyeKoordinatak.trim() !== '';
  const hasImage = !!data.fokep?.key || !!data.tovabbiKepek?.length || !!otherVideos?.length;

  useEffect(() => {
    if (hasImage) setMode('IMAGE');
    else if (hasMap) setMode('MAP');
    else setMode('PLACEHOLDER');
  }, [hasImage, hasMap]);

  useEffect(() => {
    setIsDescriptionExpanded(false);
  }, [data.alkotasAzonosito]);

  useEffect(() => {
    if (!data.leiras) {
      setDescriptionClampHeight(null);
      setIsDescriptionOverflowing(false);
      return;
    }

    const recalcDescriptionClamp = () => {
      const descriptionEl = descriptionContainerRef.current;
      const visualEl = visualColumnRef.current;
      if (!descriptionEl || !visualEl) return;

      const isTwoColumnLayout = window.matchMedia('(min-width: 1280px)').matches;
      if (!isTwoColumnLayout) {
        setDescriptionClampHeight(null);
        setIsDescriptionOverflowing(false);
        return;
      }

      const descriptionRect = descriptionEl.getBoundingClientRect();
      const visualRect = visualEl.getBoundingClientRect();
      const maxHeight = Math.floor(visualRect.bottom - descriptionRect.top);

      if (maxHeight <= 0) {
        setDescriptionClampHeight(null);
        setIsDescriptionOverflowing(false);
        return;
      }

      setDescriptionClampHeight(maxHeight);
      setIsDescriptionOverflowing(descriptionEl.scrollHeight > maxHeight + 4);
    };

    recalcDescriptionClamp();

    const observer = new ResizeObserver(recalcDescriptionClamp);
    if (descriptionContainerRef.current) observer.observe(descriptionContainerRef.current);
    if (visualColumnRef.current) observer.observe(visualColumnRef.current);
    window.addEventListener('resize', recalcDescriptionClamp);

    return () => {
      observer.disconnect();
      window.removeEventListener('resize', recalcDescriptionClamp);
    };
  }, [data.leiras, mode]);

  const mapData = hasMap
    ? convertMapData(
        [
          {
            alkotasAzonosito: data.alkotasAzonosito,
            alkotoAzonosito: data.alkotoAzonosito,
            cardType: 'creation',
            fokep: data.fokep?.key ?? null,
            fokepId: data.fokep?.id ?? null,
            fokepNev: data.fokep?.fileName ?? null,
            hivatkozas: null,
            id: data.fokep?.id ?? 0,
            koordinatak: data.keletkezesHelyeKoordinatak,
            label: data.label,
            labelYear: null,
            megjelenitendoNev: data.megjelenitendoNev ?? '',
            nev: data.nev ?? null,
            szakma: data.szakma ?? null,
            telepules: data.keletkezesHelyeCity ?? null,
            kepek: [],
            hivatkozasLista: [],
          },
        ],
        ['labelYear']
      )
    : [];

  const lightboxImages: CreationGalleryImage[] = [
    ...(data.fokep ? [data.fokep] : []),
    ...(data.tovabbiKepek || []),
  ];

  return (
    <div className="w-full flex flex-col md:gap-8">
      <div className="w-full flex flex-col xl:grid xl:grid-cols-6 items-start gap-4 lg:gap-8 pb-page pt-page">
        <div className="w-full col-span-full xl:col-span-2 self-stretch overflow-hidden flex flex-col justify-between gap-4 order-2 xl:order-1 px-4 xl:px-0">
          <div className="w-full flex flex-col gap-4">
            <div className="flex flex-col gap-1">
              <div className="font-semibold text-2xl">{data.label}</div>

              <h1 className="font-bold">{data.nev}</h1>

              <Link
                className="hover:underline transition"
                href={{
                  pathname: '/alkoto/[id]',
                  params: { id: data.alkotoAzonosito },
                }}
              >
                {data.megjelenitendoNev}
              </Link>

              {/* En attributes list rendering */}
              {/* {locale === "en" &&
                data.attributumok &&
                data.attributumok.length > 0 && (
                  <div className="flex flex-col gap-1">
                    {data.attributumok
                      .filter((attr) => attr.publikus && !attr.targyszo)
                      .map((attr) => (
                        <div key={attr.id} className="text-base">
                          <span className="">{attr.nev}</span>
                        </div>
                      ))}
                  </div>
                )} */}

              <>
                {getDataByAttributeName(data, 'Alkotó szerepe') && (
                  <div>{getDataByAttributeName(data, 'Alkotó szerepe')}</div>
                )}
                {getDataByAttributeName(data, 'Akadémikus szerepe eredménye') && (
                  <div>{getDataByAttributeName(data, 'Akadémikus szerepe eredménye')}</div>
                )}
                {getDataByAttributeName(data, 'Akadémikus szerepe') && (
                  <div>{getDataByAttributeName(data, 'Akadémikus szerepe')}</div>
                )}
                {getDataByAttributeName(data, 'Fejezetcím') && (
                  <div className="italic">{getDataByAttributeName(data, 'Fejezetcím')}</div>
                )}
                {getDataByAttributeName(data, 'Szerep') && (
                  <div className="italic">{getDataByAttributeName(data, 'Szerep')}</div>
                )}
                {getDataByAttributeName(data, 'Előadott mű címe') && (
                  <div className="italic">{getDataByAttributeName(data, 'Előadott mű címe')}</div>
                )}
              </>

              <>
                {getDataByAttributeName(data, 'Szerző') && (
                  <div>
                    {t('labels.author')} {getDataByAttributeName(data, 'Szerző')}
                  </div>
                )}
                {!getDataByAttributeName(data, 'Műfaj') &&
                  getDataByAttributeName(data, 'Alkotás eredménye') && (
                    <div>
                      {getDataByAttributeName(data, 'Alkotás eredménye')}
                      {getDataByAttributeName(data, 'Hordozó típusa')
                        ? ', ' + getDataByAttributeName(data, 'Hordozó típusa')
                        : ''}
                    </div>
                  )}
                {getDataByAttributeName(data, 'Sorozat') && (
                  <div>
                    {t('labels.seriesTitle')} {getDataByAttributeName(data, 'Sorozat')}
                  </div>
                )}
                {getDataByAttributeName(data, 'Kiadó') && (
                  <div>
                    {getDataByAttributeName(data, 'Kiadó')}
                    {getDataByAttributeName(data, 'Kiadás helye')
                      ? ', ' + getDataByAttributeName(data, 'Kiadás helye')
                      : ''}
                  </div>
                )}
                {getDataByAttributeName(data, 'Kiadás száma') && (
                  <div>{getDataByAttributeName(data, 'Kiadás száma')}</div>
                )}
                {getDataByAttributeName(data, 'Terjedelem') && (
                  <div>
                    {t('labels.extent')} {getDataByAttributeName(data, 'Terjedelem')}
                  </div>
                )}
                {getDataByAttributeName(data, 'Borítótervező') && (
                  <div>
                    {t('labels.coverDesigner')} {getDataByAttributeName(data, 'Borítótervező')}
                  </div>
                )}
                {getDataByAttributeName(data, 'Nyelv') && (
                  <div>
                    {t('labels.publicationLanguage')} {getDataByAttributeName(data, 'Nyelv')}
                  </div>
                )}
                {getDataByAttributeName(data, 'Műfaj') && (
                  <div>{getDataByAttributeName(data, 'Műfaj')}</div>
                )}
                {getDataByAttributeName(data, 'Rendező') && (
                  <div>
                    {t('labels.director')} {getDataByAttributeName(data, 'Rendező')}
                  </div>
                )}
                {getDataByAttributeName(data, 'Film műfaja') && (
                  <div>{getDataByAttributeName(data, 'Film műfaja')}</div>
                )}
                {getDataByAttributeName(data, 'Intézmény neve') && (
                  <div>{getDataByAttributeName(data, 'Intézmény neve')}</div>
                )}
                {getDataByAttributeName(data, 'Filmművészti alkotás státusza') && (
                  <div>{getDataByAttributeName(data, 'Filmművészti alkotás státusza')}</div>
                )}
                {getDataByAttributeName(data, 'Gyártó stúdió') && (
                  <div>{getDataByAttributeName(data, 'Gyártó stúdió')}</div>
                )}
                {getDataByAttributeName(data, 'Kapcsolódó szerző') && (
                  <div>{getDataByAttributeName(data, 'Kapcsolódó szerző')}</div>
                )}
              </>

              {data.alkototars && data.alkototars.length > 0 && (
                <div>
                  {t('labels.creators')}{' '}
                  {data.alkototars?.map((item, index) => (
                    <React.Fragment key={item.azonosito}>
                      {index > 0 && ', '}
                      <Link
                        href={{
                          pathname: '/alkoto/[id]',
                          params: { id: item.azonosito },
                        }}
                        className="hover:underline transition"
                      >
                        {item.nev}
                      </Link>
                    </React.Fragment>
                  ))}
                </div>
              )}
              {data.keletkezesHelyeCity && (
                <Link
                  href={
                    (getSearchUrl(
                      data.keletkezesHelyeCity,
                      'alkotas',
                      null,
                      data.keletkezesHelyeCity,
                      'telepules'
                    ) || '') as never
                  }
                  className="italic hover:underline"
                >
                  {data.keletkezesHelyeCity}
                </Link>
              )}
              {data.leiras && (
                <>
                  {locale === 'en' && data.gepiForditas && (
                    <p className="text-xs lg:text-md lg:text-base text-red-500 font-medium">
                      The following text is based on an automated translation of the original
                      document.
                    </p>
                  )}

                  <div
                    className="relative mt-1"
                    ref={descriptionContainerRef}
                    style={
                      !isDescriptionExpanded && descriptionClampHeight
                        ? {
                            maxHeight: `${descriptionClampHeight}px`,
                            overflow: 'hidden',
                          }
                        : undefined
                    }
                  >
                    <div
                      className="max-w-full overflow-hidden break-words [&_*]:max-w-full [&_img]:h-auto [&_img]:w-full [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto [&_iframe]:max-w-full"
                      style={
                        !isDescriptionExpanded && isDescriptionOverflowing
                          ? {
                              WebkitMaskImage:
                                'linear-gradient(to bottom, black 0%, black 62%, transparent 100%)',
                              maskImage:
                                'linear-gradient(to bottom, black 0%, black 62%, transparent 100%)',
                            }
                          : undefined
                      }
                      dangerouslySetInnerHTML={{ __html: data.leiras }}
                    />

                    {!isDescriptionExpanded &&
                      isDescriptionOverflowing &&
                      descriptionClampHeight && (
                        <div className="pointer-events-none absolute inset-x-0 bottom-0 h-40 bg-gradient-to-t from-white via-white/90 to-transparent">
                          <div className="absolute inset-x-0 bottom-0 flex items-end px-1 pb-1">
                            <button
                              type="button"
                              onClick={() => setIsDescriptionExpanded(true)}
                              className="pointer-events-auto inline-flex items-center gap-1.5 text-sm font-semibold uppercase tracking-wide text-mma-blue underline underline-offset-2 hover:text-mma-yellow transition-colors"
                            >
                              <span>{locale === 'en' ? 'Read more' : 'Tovább olvasom'}</span>
                              <IoArrowForward className="text-sm" />
                            </button>
                          </div>
                        </div>
                      )}

                    {isDescriptionExpanded && isDescriptionOverflowing && (
                      <div className="mt-6">
                        <button
                          type="button"
                          onClick={() => setIsDescriptionExpanded(false)}
                          className="inline-flex items-center gap-1.5 text-sm font-semibold uppercase tracking-wide text-mma-blue underline underline-offset-2 hover:text-mma-yellow transition-colors"
                        >
                          <IoArrowForward className="text-sm rotate-180" />
                          <span>{locale === 'en' ? 'Close' : 'Bezárás'}</span>
                        </button>
                      </div>
                    )}
                  </div>
                </>
              )}
            </div>
          </div>
        </div>

        <div
          className="w-full col-span-full xl:col-span-4 order-1 xl:order-2"
          ref={visualColumnRef}
        >
          {hasMap && hasImage ? (
            <div className="mb-3 flex justify-end">
              <div className="inline-flex items-center border border-mma-blue/25 bg-white">
                <button
                  type="button"
                  onClick={() => setMode('IMAGE')}
                  aria-label={t('viewToggle.gallery')}
                  title={t('viewToggle.gallery')}
                  className={
                    'inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold uppercase tracking-wide transition-colors ' +
                    (mode === 'IMAGE'
                      ? 'bg-mma-blue text-white'
                      : 'text-mma-blue/85 hover:bg-mma-blue/10')
                  }
                >
                  <Images size={14} />
                  <span>{t('viewToggle.gallery')}</span>
                </button>
                <button
                  type="button"
                  onClick={() => setMode('MAP')}
                  aria-label={t('viewToggle.map')}
                  title={t('viewToggle.map')}
                  className={
                    'inline-flex items-center gap-1.5 border-l border-mma-blue/20 px-3 py-1.5 text-xs font-semibold uppercase tracking-wide transition-colors ' +
                    (mode === 'MAP'
                      ? 'bg-mma-blue text-white'
                      : 'text-mma-blue/85 hover:bg-mma-blue/10')
                  }
                >
                  <MapPinned size={14} />
                  <span>{t('viewToggle.map')}</span>
                </button>
              </div>
            </div>
          ) : null}

          {mode === 'IMAGE' && (
            <Gallery
              images={lightboxImages}
              hasArrows
              videoId={otherVideos?.[0]?.hivatkozas}
              videoForrasa={otherVideos?.[0]?.forrasa}
            />
          )}

          {mode === 'MAP' && hasMap && (
            <CreationMap
              className="aspect-square border border-mma-blue/10 sm:aspect-video"
              data={mapData}
              fitBoundsKey={data.alkotasAzonosito}
              enablePointCards={false}
            />
          )}

          {mode === 'PLACEHOLDER' && (
            <div className="aspect-square sm:aspect-video bg-gray-100 flex items-center justify-center">
              <span className="text-gray-500 font-bold text-lg sm:text-xl">
                {t('noImageAvailable')}
              </span>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default CreationClient;
