/* eslint-disable @typescript-eslint/no-explicit-any */
import { Metadata } from 'next';
import { notFound } from 'next/navigation';

import { IoHomeOutline } from 'react-icons/io5';

import { getCreatorDataCached } from '@/services/creatorsCache';

import { BreadcrumbItem } from '@/components/common/Breadcrumbs';
import BreadcrumbsShell from '@/components/common/BreadcrumbsShell';
import FloatingShareRail from '@/components/common/FloatingShareRail';
import CreatorHeaderRow from '@/components/creators/CreatorHeaderRow';
import CreatorMenuBar from '@/components/creators/CreatorMenuBar';
import { getFullMembershipString, removeHtmlTags } from '@/utils/creatorHelpers';
import { getMetaAttribute110ByKey } from '@/utils/filterUtils';

import { asHref } from '@/i18n/asHref';

// todo
export const revalidate = 60; // revalidate every 60 seconds

// todo
// export async function generateStaticParams() {
//   // fetch all creator ids??
//   const creators = await getAllCreatorIds(); // pl. [{ id: "AL0000001" }, ...]
//   return creators.map((creator: any) => ({ id: creator.id }));
// }

export default async function CreatorLayout({
  params,
  children,
}: {
  children: React.ReactNode;
  params: Promise<{ id: string; locale: string }>;
}) {
  const { id, locale } = await params;
  if (!id) return notFound();

  const creator = await getCreatorDataCached(id);
  if (!creator) return notFound();

  const breadcrumbItems: BreadcrumbItem[] = [
    {
      label: locale === 'en' ? 'Home' : 'Főoldal',
      href: { pathname: '/' },
      icon: <IoHomeOutline />,
      ariaLabel: locale === 'en' ? 'Home' : 'Főoldal',
    },
    {
      label: locale === 'en' ? 'Creators' : 'Alkotók',
      href: { pathname: '/alkotok' },
    },
  ];

  if (creator.muveszetiAgEnum) {
    const meta = getMetaAttribute110ByKey(creator.muveszetiAgEnum);
    const prettyKey = meta?.prettyKey;
    const label = creator.muveszetiAg || meta?.name || null;
    if (prettyKey && label) {
      breadcrumbItems.push({
        label,
        href: asHref(`/alkotok/${prettyKey}`),
        hideBelow: 'lg',
      });
    }
  }

  breadcrumbItems.push({
    label: creator.nev || '',
    href: {
      pathname: '/alkoto/[id]',
      params: { id: creator.alkotoAzonosito },
    },
  });

  // Schema.org structured data for the creator
  const regex = /(<([^>]+)>)/gi;
  const schemaPerson = {
    '@context': 'https://schema.org',
    '@type': 'Person',
    name: creator.nev,
    birthDate: creator.szuletesiIdo ?? '',
    birthPlace: creator.szuletesiHely,
    ...(creator.elhalalozasIdeje && {
      deathDate: creator.elhalalozasIdeje,
      deathPlace: creator.elhalalozasHelye,
    }),
    description: creator.szakmaOndef?.replace(regex, ''),
    image: creator.profilkep?.key
      ? `${process.env.NEXT_PUBLIC_API_URL}/imageRepository/getImage?key=${creator.profilkep?.key}`
      : undefined,
    url: `${process.env.NEXT_PUBLIC_BASE_URL}/alkoto/${creator.alkotoAzonosito}`,
  };

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(schemaPerson) }}
      />
      <FloatingShareRail
        title={creator.nev || ''}
        description={removeHtmlTags(creator.szakmaOndef || '')}
        position="left-center"
      />
      <FloatingShareRail
        title={creator.nev || ''}
        description={removeHtmlTags(creator.szakmaOndef || '')}
        layout="horizontal"
        position="bottom-center"
        hideOnMobile={false}
        showNativeShare={true}
        showEmail={false}
        className="lg:hidden"
      />

      <div className="w-full flex flex-col gap-4 pb-page px-site">
        <BreadcrumbsShell baseItems={breadcrumbItems} sticky>
          <div className="w-full flex flex-col gap-4">
            <CreatorHeaderRow creator={creator} quote={creator.palyakepLead} />
          </div>
          <CreatorMenuBar creator={creator} />
          <div className="w-full flex flex-col gap-4 lg:gap-6">{children}</div>
        </BreadcrumbsShell>
      </div>
    </>
  );
}

// --- METADATA ---
export async function generateMetadata({ params }: any): Promise<Metadata> {
  const { id } = await params;
  const item = await getCreatorDataCached(id);
  if (!item) return {};

  const title = `${item.nev || ''} ${item.szakma || ''}`.trim();
  const profession = removeHtmlTags(item.szakmaOndef || '');
  const birthPlace = item.szuletesiHely || '';
  const birthDate = item.szuletesiIdo || '';
  const hasDeath = !!item.elhalalozasIdeje;
  const deathPlace = item.elhalalozasHelye;
  const deathDate = item.elhalalozasIdeje;
  const section = item.tagozat || '';
  let membership = '';
  const firstMemberShip = item.mmaTagsagLista?.[0];
  if (firstMemberShip) {
    membership = getFullMembershipString(firstMemberShip);
  }

  let lifeSpan = `született ${birthPlace} (${birthDate})`;
  if (hasDeath) {
    lifeSpan += `, elhunyt${deathPlace ? ' ' + deathPlace : ''}${
      deathDate ? ', ' + deathDate : ''
    }`;
  }

  let description = `${title} ${profession}, ${lifeSpan}`;
  if (membership) {
    description += ' ' + membership;
  } else {
    description += `. Az MMA ${section} tagja.`;
  }

  description = description.replace(/\.{2,}/g, '.').replace(/([,;])\./g, '.');
  const ogDescription = `${title} ${profession} életrajza és alkotásai az A-Z OPUS művészeti életút adatbázisban.`;

  const canonical = `/alkoto/${item.alkotoAzonosito}`;
  const apiUrl = process.env.NEXT_PUBLIC_API_URL?.replace(/\/$/, '');
  const galleryImage = item.galeria?.[0] ?? null;
  const rawImage =
    apiUrl && galleryImage?.key
      ? `${apiUrl}/imageRepository/getImage?key=${encodeURIComponent(galleryImage.key)}`
      : null;
  const imageRatio =
    galleryImage && galleryImage.width > 0 && galleryImage.height > 0
      ? galleryImage.width / galleryImage.height
      : null;
  const isNearSquare = imageRatio !== null && imageRatio >= 0.85 && imageRatio <= 1.15;
  const image = rawImage
    ? isNearSquare
      ? `/alkoto/${item.alkotoAzonosito}/og-img`
      : rawImage
    : null;

  return {
    title,
    description,
    keywords: [
      title,
      profession,
      `${title} alkotásai`,
      `${title} életrajz`,
      'magyar művész',
      section,
      birthPlace,
      'kortárs művészet',
      'mma művész',
      'magyar művészeti akadémia',
    ],

    alternates: {
      canonical,
    },
    openGraph: {
      url: canonical,
      title,
      description: ogDescription,
      images: image ? [image] : undefined,
      type: 'profile',
      locale: 'hu_HU',
    },
    twitter: {
      card: 'summary_large_image',
      site: '@azopus',
      title,
      description,
      images: image ? [image] : undefined,
    },
  };
}

// kép forrása: xy
// fotós neve og desc ha van // kép forrása
//
