import { cache } from 'react';

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

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

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

import Breadcrumbs, { BreadcrumbItem } from '@/components/common/Breadcrumbs';
import FloatingShareRail from '@/components/common/FloatingShareRail';
import { removeHtmlTags } from '@/utils/creatorHelpers';
import { getMetaAttribute110ByKey } from '@/utils/filterUtils';

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

import CreationClient from '@/app/[locale]/alkotas/[id]/CreationClient';
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 = await getCreationByIdCached(id);

  if (!item) return notFound();

  // get related creations
  let featuredCreations = [];
  const personId = item.alkotoAzonosito;
  if (personId) {
    const response = await getFeaturedCreations(personId, 16);
    // filter out the current creation
    featuredCreations = response
      ? response.filter((x: CreationListItem) => x.alkotasAzonosito !== id)
      : [];
  }

  const breadcrumbItems: BreadcrumbItem[] = [
    {
      label: locale === 'en' ? 'Home' : 'Főoldal',
      href: { pathname: '/' },
      icon: <IoHomeOutline />,
      ariaLabel: locale === 'en' ? 'Home' : 'Főoldal',
    },
    {
      label: locale === 'en' ? 'Creations' : 'Alkotások',
      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 (item.alkotoAzonosito && item.megjelenitendoNev) {
    breadcrumbItems.push({
      label: item.megjelenitendoNev,
      href: {
        pathname: '/alkoto/[id]',
        params: { id: item.alkotoAzonosito },
      },
      hideBelow: 'lg',
    });
  }

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

  const shareTitle = [item.megjelenitendoNev, item.nev].filter(Boolean).join(' - ');
  const shareDescription = item.leiras ? removeHtmlTags(item.leiras).substring(0, 220) : '';

  return (
    <>
      <FloatingShareRail title={shareTitle} description={shareDescription} position="left-center" />
      <FloatingShareRail
        title={shareTitle}
        description={shareDescription}
        layout="horizontal"
        position="bottom-center"
        hideOnMobile={false}
        showNativeShare={true}
        showEmail={false}
        className="lg:hidden"
      />
      <div className="px-site">
        <Breadcrumbs items={breadcrumbItems} sticky />
        <CreationClient
          creation={item}
          featuredCreations={featuredCreations}
          locale={resolvedLocale}
        />
      </div>
    </>
  );
}

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

  const title = item.nev || '';

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

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

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

  const canonical = `/alkotas/${item.alkotasAzonosito}`;
  const image = item.fokep?.key
    ? `${process.env.NEXT_PUBLIC_API_URL}/imageRepository/getImage?key=${item.fokep.key}`
    : undefined;

  return {
    title,
    description,
    alternates: {
      canonical,
    },
    openGraph: {
      url: canonical,
      title,
      description: metaDescription,
      images: image ? [image] : [],
      type: 'article',
      locale: locale || defaultLocale,
    },
    twitter: {
      card: 'summary_large_image',
      site: '@azopus',
      title,
      description: metaDescription,
      images: image ? [image] : [],
    },
  };
}
