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

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

import { getCreationList } from '@/services/creations';

import Breadcrumbs, { BreadcrumbItem } from '@/components/common/Breadcrumbs';
import { convertFromPrettyKey, metaAttributes110 } from '@/utils/filterUtils';

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

import CreationListClient from '@/app/[locale]/alkotasok/CreationListClient';
import { Link } from '@/i18n/navigation';

export async function generateStaticParams() {
  return metaAttributes110.map((category) => ({
    category: category.prettyKey,
  }));
}

export const revalidate = 259200; // 3 days in seconds

const CHUNK_SIZE = 3000;

export default async function CreationListPage({
  params,
}: {
  params: Promise<{ category: string; locale: string }>;
}) {
  const { category, locale } = await params;

  const key = convertFromPrettyKey(category);
  if (!key) return null;

  // create chunks to be able to fetch-cache >2mb data
  const categoryInfo = metaAttributes110.find((cat) => cat.prettyKey === category);

  const chunksCount = categoryInfo?.dataChunks || 4;

  const offsets = Array.from({ length: chunksCount }, (_, i) => i * CHUNK_SIZE);

  const chunks = await Promise.all(
    offsets.map((o) =>
      getCreationList({
        contentType: [key],
        firstResult: o,
        maxResults: CHUNK_SIZE,
      })
    )
  );

  const creations = chunks.flat().filter(Boolean);

  // Extract and process years
  const years = creations
    .map((c: CreationListItem) => c.labelYear)
    .filter((year: number | null): year is number => typeof year === 'number' && year !== 1000);

  const maxYear = years.length > 0 ? Math.max(...years) : new Date().getFullYear();
  const minYear = years.length > 0 ? Math.min(...years) : maxYear - 100;

  // Get unique years sorted descending (newest first)
  const availableYears: number[] = [...new Set<number>(years)].sort((a, b) => b - a);

  const t = await getTranslations('navigation.menu');
  const tCategories = await getTranslations('categories');
  const tMapView = await getTranslations('mapViewPage');
  const categoryName = categoryInfo ? tCategories(categoryInfo.labelKey) : t('creations');

  const breadcrumbItems = [
    {
      label: locale === 'en' ? 'Home' : 'Főoldal',
      href: { pathname: '/' },
      icon: <IoHomeOutline />,
      ariaLabel: locale === 'en' ? 'Home' : 'Főoldal',
    },
    {
      label: t('creations'),
      href: { pathname: '/alkotasok' },
    },
    {
      label: categoryName,
    },
  ] satisfies BreadcrumbItem[];

  return (
    <>
      <Breadcrumbs
        items={breadcrumbItems}
        className="px-site"
        sticky
        rightSlot={
          <Link
            href={`/terkep/${category}` as never}
            className="inline-flex h-full items-center gap-1.5 bg-white/90 px-2 sm:px-3 text-[11px] sm:text-[12px] font-semibold uppercase tracking-[0.3em] text-[#151720]/75 transition-colors hover:bg-white hover:text-[#151720]"
          >
            <MapPinned size={14} />
            <span className="hidden sm:inline">{tMapView('mapView')}</span>
          </Link>
        }
      />
      <CreationListClient
        title={t('creations')}
        creations={creations}
        min={minYear}
        max={maxYear}
        initialYear={maxYear}
        availableYears={availableYears}
      />
    </>
  );
}

// ------ META DATA ------
export async function generateMetadata({
  params,
}: {
  params: Promise<{ category: string }>;
}): Promise<Metadata> {
  const { category } = await params;

  // Find category info
  const categoryInfo = metaAttributes110.find((cat) => cat.prettyKey === category);

  const tCategories = await getTranslations('categories');
  const tMetadata = await getTranslations('creationListPage.metadata');
  const categoryName = categoryInfo ? tCategories(categoryInfo.labelKey) : 'Alkotások';

  return {
    title: categoryName,
    description: tMetadata('descriptionTemplate', { categoryName }),
    alternates: {
      canonical: `/alkotasok/${category}`,
    },
    openGraph: {
      title: categoryName,
      description: tMetadata('descriptionTemplate', { categoryName }),
      type: 'website',
    },
  };
}
