import { cache } from 'react';

import { Metadata } from 'next';
import { getTranslations } from 'next-intl/server';
import { notFound } from 'next/navigation';

import { getCreationById, getCreatorRecommendations } from '@/services/creations';

import Breadcrumbs, { BreadcrumbItem } from '@/components/common/Breadcrumbs';
import CreationNavButtons, { CreationPagerBar } from '@/components/common/CreationNavButtons';
import { shuffle } from '@/utils/array';
import {
  getCreationCreatorDisplayName,
  getCreationCreatorProfessionDisplayName,
  getCreationCreators,
  getPrimaryCreationCreator,
} from '@/utils/creationHelpers';
import { removeHtmlTags } from '@/utils/creatorHelpers';
import { getMetaAttribute110ByKey } from '@/utils/filterUtils';
import { buildMediaUrl } from '@/utils/images';
import { getLocalizedAlternates, getLocalizedUrl, resolveAppLocale } from '@/utils/seo';

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

import CreationClientWrapper from '@/app/[locale]/alkotas/[id]/CreationClientWrapper';
import { defaultLocale, isAppLocale } from '@/config/i18n';
import { asHref } from '@/i18n/asHref';

// cache the creation data to avoid multiple API calls
const getCreationByIdCached = cache(getCreationById);

interface PageParams {
  params: Promise<{ id: string; locale: string }>;
}

export default async function CreationPage({ params }: PageParams) {
  const { id, locale } = await params;
  const resolvedLocale = isAppLocale(locale) ? locale : defaultLocale;
  const item: CreationPageItem | null = await getCreationByIdCached(id);

  if (!item) return notFound();

  const creators = getCreationCreators(item);
  const primaryCreator = getPrimaryCreationCreator(item);
  const creatorDisplayName = getCreationCreatorDisplayName(item);

  // SSR the initial "recommended" tab (creator-based pool) so the recommender
  // renders with content on first paint; tab switches re-fetch client-side.
  let initialRecommendations: CreationListItem[] = [];
  if (primaryCreator?.alkotoAzonosito) {
    const pool = await getCreatorRecommendations(primaryCreator.alkotoAzonosito);
    // mirror the API route: drop the viewed creation, randomize, cap at 16 — so
    // the SSR'd first tab matches what a client re-fetch would produce.
    initialRecommendations = shuffle(
      pool.filter((rec) => rec.alkotasAzonosito !== item.alkotasAzonosito)
    ).slice(0, 16);
  }

  const tNavigation = await getTranslations('navigation.menu');
  const breadcrumbItems: BreadcrumbItem[] = [
    {
      label: tNavigation('creations'),
      href: { pathname: '/alkotasok' },
    },
  ];

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

  if (primaryCreator && creatorDisplayName) {
    breadcrumbItems.push({
      label: creatorDisplayName,
      href:
        creators.length === 1
          ? {
              pathname: '/alkoto/[id]',
              params: { id: primaryCreator.alkotoAzonosito },
            }
          : undefined,
      hideBelow: 'lg',
    });
  }

  breadcrumbItems.push({
    label: item.nev || '',
  });

  return (
    <>
      <CreationNavButtons pager={item.elozo_kovetkezo} />

      <Breadcrumbs
        items={breadcrumbItems}
        sticky
        className="px-site bg-white/90"
        innerClassName="bg-transparent"
        rightSlot={<CreationPagerBar pager={item.elozo_kovetkezo} />}
      />
      <CreationClientWrapper
        creation={item}
        initialRecommendations={initialRecommendations}
        recommendedCreatorIdentifier={
          initialRecommendations.length > 0 ? (primaryCreator?.alkotoAzonosito ?? null) : null
        }
        locale={resolvedLocale}
      />
    </>
  );
}

export async function generateMetadata({ params }: PageParams): Promise<Metadata> {
  const { id, locale } = await params;
  const resolvedLocale = resolveAppLocale(locale);
  const item: CreationPageItem | null = await getCreationByIdCached(id);
  if (!item) return {};
  const t = await getTranslations('creationPage.metadata');

  const title = item.nev || '';
  const creatorDisplayName = getCreationCreatorDisplayName(item);
  const creatorProfessionDisplayName = getCreationCreatorProfessionDisplayName(item);

  // desc: {name} {prof},  {evszam}, {telepules},
  const nameAndJob = [creatorDisplayName, creatorProfessionDisplayName].filter(Boolean).join(' ');

  const rest = [item.label, item.keletkezesHelyeCity].filter(Boolean).join(', ');

  const metaDescription = [nameAndJob, rest].filter(Boolean).join(', ');
  const description = [
    creatorDisplayName,
    item.nev,
    item.keletkezesHelyeCity,
    item.label,
    item.leiras
      ? removeHtmlTags(item.leiras)?.substring(0, 200)
      : t('defaultDescription', { title }),
  ]
    .filter(Boolean)
    .join(', ');

  const href = {
    pathname: '/alkotas/[id]',
    params: { id: item.alkotasAzonosito },
  };
  const url = getLocalizedUrl(resolvedLocale, href);

  const image = item.fokep?.id ? `${buildMediaUrl(item.fokep.id, 'w1024')}` : undefined;

  return {
    title,
    description,
    alternates: getLocalizedAlternates(locale, href),
    openGraph: {
      url,
      title,
      description: metaDescription,
      images: image ? [image] : [],
      type: 'article',
      locale: resolvedLocale,
    },
    twitter: {
      card: 'summary_large_image',
      site: '@azopus',
      title,
      description: metaDescription,
      images: image ? [image] : [],
    },
  };
}
