import React from 'react';

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

import { IoHomeOutline } from 'react-icons/io5';
import { MdLocationPin, MdSchedule } from 'react-icons/md';

import { getEventBySlug } from '@/services/events';

import Breadcrumbs from '@/components/common/Breadcrumbs';
import type { BreadcrumbItem } from '@/components/common/Breadcrumbs';
import FloatingShareRail from '@/components/common/FloatingShareRail';
import EventImageDialog from '@/components/events/EventImageDialog';
import {
  getEventCultTypeLabel,
  getEventTimeIntervalString,
  getInstitutionCoordinates,
  getInstitutionLocationString,
} from '@/utils/eventHelpers';
import { getFullSizeImageByKey } from '@/utils/images';

import { getCategoryColors } from '@/config/calendarCategories';
import { Link } from '@/i18n/navigation';

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

const EventDetailsPage = async ({ params }: PageParams) => {
  const { slug, locale } = await params;
  if (!slug) return null;

  const event = await getEventBySlug({ slug });
  if (!event) return notFound();

  const institutionField = event.intezmeny?.[0];
  const institutionAddress =
    institutionField?.szervezetiEgyseg?.cim || institutionField?.intezmeny?.intezmenyCime;
  const locationString = institutionField ? getInstitutionLocationString(institutionField) : null;
  const coordinates = institutionAddress ? getInstitutionCoordinates(institutionAddress) : null;
  const dateLabel = getEventTimeIntervalString(event, true, locale);
  const categoryLabel = event.esemenyKategoria?.[0]?.nev || getEventCultTypeLabel(event) || 'Egyeb';
  const categoryColor = getCategoryColors(categoryLabel);
  const imageUrl = event.fokep?.key
    ? getFullSizeImageByKey(event.fokep.key)
    : event.kepLink || null;
  const t = await getTranslations('singleEventPage');
  const navT = await getTranslations('navigation.menu');
  const infoLabel = t('info');
  const ticketLabel = t('ticket');
  const peopleLabel = t('affectedCreators');
  const breadcrumbItems = [
    {
      label: locale === 'en' ? 'Home' : 'Főoldal',
      href: { pathname: '/' },
      icon: <IoHomeOutline />,
      ariaLabel: locale === 'en' ? 'Home' : 'Főoldal',
    },
    {
      label: navT('programs'),
      href: { pathname: '/programok' },
    },
    {
      label: event.nev,
    },
  ] satisfies BreadcrumbItem[];

  return (
    <section className="relative min-h-screen w-full overflow-hidden bg-white text-[#151720]">
      <FloatingShareRail
        position="left-center"
        title={event.nev}
        description={event.leiras?.replace(/<[^>]+>/g, '') || ''}
        showGoogleCalendar={true}
        eventTitle={event.nev}
        eventStartDate={event.kezdete}
        eventEndDate={event.vege || undefined}
        eventLocation={locationString}
        eventDescription={event.leiras?.replace(/<[^>]+>/g, '') || ''}
      />
      <FloatingShareRail
        position="bottom-center"
        layout="horizontal"
        hideOnMobile={false}
        className="lg:hidden"
        title={event.nev}
        description={event.leiras?.replace(/<[^>]+>/g, '') || ''}
        showNativeShare={true}
        showEmail={false}
        showGoogleCalendar={true}
        eventTitle={event.nev}
        eventStartDate={event.kezdete}
        eventEndDate={event.vege || undefined}
        eventLocation={locationString}
        eventDescription={event.leiras?.replace(/<[^>]+>/g, '') || ''}
      />
      <div className="px-site pt-2 lg:pt-4">
        <div className="mx-auto max-w-boxed">
          <Breadcrumbs items={breadcrumbItems} sticky={false} />
        </div>
      </div>
      <div className="relative px-site pb-8 lg:pt-4 lg:pb-12">
        <div className="mx-auto flex max-w-boxed flex-col gap-8">
          <div className="flex flex-col gap-4">
            {categoryLabel && (
              <span
                className="inline-flex w-fit items-center px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.3em] text-white"
                style={{ backgroundColor: categoryColor.color }}
              >
                {categoryLabel}
              </span>
            )}

            <h1 className="type-section-title text-2xl sm:text-4xl lg:text-5xl text-[#151720]">
              {event.nev}
            </h1>

            {/* Date and Location */}
            <div className="flex flex-col gap-4">
              <div className="flex flex-col gap-3 text-sm font-semibold uppercase tracking-[0.14em] text-[#151720]/70 sm:flex-row sm:flex-wrap sm:items-center sm:tracking-[0.2em]">
                {dateLabel && (
                  <span className="inline-flex items-center gap-2 leading-snug">
                    <MdSchedule className="shrink-0 text-lg lg:text-2xl text-[#151720]/60" />
                    <span>{dateLabel}</span>
                  </span>
                )}
                {locationString && (
                  <span className="inline-flex items-center gap-2 leading-snug">
                    <MdLocationPin className="shrink-0 text-lg lg:text-2xl text-[#151720]/60" />
                    <span>{locationString}</span>
                  </span>
                )}
              </div>
            </div>
          </div>

          <div
            className={[
              imageUrl
                ? 'grid items-start gap-8 lg:grid-cols-[1.05fr_1fr] lg:gap-10'
                : 'grid gap-8',
            ]
              .filter(Boolean)
              .join(' ')}
          >
            <div className={imageUrl ? 'min-w-0 flex flex-col gap-6' : 'flex flex-col gap-6'}>
              {event.leiras && (
                <div className="text-base font-medium leading-relaxed text-[#151720]/75">
                  <div dangerouslySetInnerHTML={{ __html: event.leiras }} />
                </div>
              )}

              {event.szemely && event.szemely.length > 0 && (
                <div className="flex flex-wrap items-center gap-2 text-sm font-semibold uppercase tracking-[0.15em] text-[#151720]/70">
                  <span>{peopleLabel}:</span>
                  {event.szemely.map((person) => (
                    <Link
                      key={person.id}
                      href={{
                        pathname: '/alkoto/[id]',
                        params: { id: person.szemely.alkotoAzonosito },
                      }}
                      className="inline-flex items-center gap-2 bg-mma-yellow/90 px-3 py-1 text-xs font-semibold text-[#151720] transition hover:bg-mma-yellow/80 lg:text-sm"
                    >
                      <span className="uppercase tracking-[0.12em]">{person.szemely.name}</span>
                      {person.szemely.szakma?.name && (
                        <span className="text-mma-blue lowercase tracking-normal">
                          {person.szemely.szakma.name}
                        </span>
                      )}
                    </Link>
                  ))}
                </div>
              )}

              {(event.infoUrl || event.jegyUrl) && (
                <div className="flex flex-wrap gap-3">
                  {event.infoUrl && (
                    <a
                      href={event.infoUrl}
                      target="_blank"
                      rel="noreferrer"
                      className="inline-flex items-center gap-3 border border-[#151720]/40 bg-white/70 px-5 py-2 text-xs font-semibold uppercase tracking-[0.3em] text-[#151720]/80 transition hover:bg-[#151720]/10"
                    >
                      {infoLabel}
                      <span className="h-px w-6 bg-[#151720]/60" />
                    </a>
                  )}
                  {event.jegyUrl && (
                    <a
                      href={event.jegyUrl}
                      target="_blank"
                      rel="noreferrer"
                      className="inline-flex items-center gap-3 border border-[#151720]/40 bg-white/70 px-5 py-2 text-xs font-semibold uppercase tracking-[0.3em] text-[#151720]/80 transition hover:bg-[#151720]/10"
                    >
                      {ticketLabel}
                      <span className="h-px w-6 bg-[#151720]/60" />
                    </a>
                  )}
                </div>
              )}
            </div>

            {imageUrl && (
              <EventImageDialog
                imageUrl={imageUrl}
                eventName={event.nev}
                locale={locale}
                imageWidth={event.fokep?.width}
                imageHeight={event.fokep?.height}
                className="mobile-full-bleed order-first lg:order-last"
              />
            )}
          </div>

          {coordinates && (
            <div className="mobile-full-bleed rounded-2xl border border-[#151720]/10 bg-white shadow-[0_30px_80px_-60px_rgba(20,25,40,0.25)]">
              <div className="h-80 overflow-hidden lg:h-96">
                <iframe
                  title={locale === 'en' ? 'Google Maps' : 'Google térkép'}
                  width="100%"
                  height="100%"
                  frameBorder="0"
                  style={{ border: 0 }}
                  src={`https://www.google.com/maps?q=${encodeURIComponent(
                    coordinates
                  )}&output=embed`}
                  allowFullScreen
                />
              </div>
            </div>
          )}
        </div>
      </div>
    </section>
  );
};

export async function generateMetadata({ params }: PageParams): Promise<Metadata> {
  const { slug, locale } = await params;
  const t = await getTranslations('singleEventPage.metaData');

  try {
    const event = await getEventBySlug({ slug });

    if (!event) {
      return {
        title: t('eventNotFound'),
      };
    }

    const eventUrl = `https://azopus.hu/program/${event.url || ''}`;
    const eventImage = event.fokep?.key
      ? getFullSizeImageByKey(event.fokep.key)
      : event.kepLink || undefined;

    const dateLocale = locale === 'en' ? 'en-US' : 'hu-HU';
    const formattedStartDate = new Date(event.kezdete).toLocaleDateString(dateLocale, {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
    const formattedEndDate = event.vege
      ? new Date(event.vege).toLocaleDateString(dateLocale, {
          year: 'numeric',
          month: 'long',
          day: 'numeric',
        })
      : null;
    const eventDate =
      formattedEndDate && formattedEndDate !== formattedStartDate
        ? `${formattedStartDate} - ${formattedEndDate}`
        : formattedStartDate;

    const institutionField = event.intezmeny?.[0];
    const locationAddress =
      institutionField?.szervezetiEgyseg?.cim || institutionField?.intezmeny?.intezmenyCime || null;
    const locationCity = (
      locale === 'en'
        ? locationAddress?.cityEn || locationAddress?.city
        : locationAddress?.city || locationAddress?.cityEn
    )?.trim();

    const eventCategory = event.esemenyKategoria?.[0]?.nev;
    const eventTitle = eventCategory ? `${eventCategory} | ${event.nev}` : event.nev;

    // title: kiállítás | programcíme
    // desc: település, időpont, érintett alkotök: yx, zdx
    const affectedCreators =
      event.szemely && event.szemely.length > 0
        ? `${t('affectedCreators')}: ${event.szemely.map((person) => person.szemely.name).join(', ')}`
        : '';
    const eventDescription = [eventDate, locationCity, affectedCreators]
      .filter((part) => Boolean(part && part.trim().length > 0))
      .join(', ');

    return {
      title: eventTitle,
      description: eventDescription || eventTitle,
      alternates: {
        canonical: `/program/${event.url || event.id}`,
      },
      openGraph: {
        title: eventTitle,
        description: eventDescription || eventTitle,
        images: eventImage ? [{ url: eventImage }] : [],
        type: 'website',
        url: eventUrl,
        locale: locale,
        siteName: 'A-Z OPUS',
      },
      twitter: {
        card: 'summary_large_image',
        title: eventTitle,
        description: eventDescription || eventTitle,
        images: eventImage ? [eventImage] : [],
      },
    };
  } catch (error) {
    console.error('Failed to generate metadata:', error);
    return {
      title: t('event'),
    };
  }
}

export default EventDetailsPage;
