import { notFound } from 'next/navigation';
import Image from 'next/image';
import { getTranslations } from 'next-intl/server';
import { prisma } from '@/lib/prisma';
import { Container } from '@/components/ui/container';
import { Button } from '@/components/ui/button';
import { Reveal } from '@/components/ui/reveal';
import { buildMetadata } from '@/lib/seo';
import { JsonLd, breadcrumbSchema } from '@/lib/schema-org';
import type { Locale } from '@/i18n/config';

const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL ?? 'http://localhost:3000';

async function getService(slug: string, locale: Locale) {
  const service = await prisma.service.findUnique({
    where: { slug },
    include: {
      translations: { where: { locale } },
      faqs: { include: { translations: { where: { locale } } } }
    }
  });
  if (!service || !service.translations[0]) return null;
  return { ...service, t: service.translations[0] };
}

export async function generateMetadata({
  params: { locale, slug }
}: {
  params: { locale: Locale; slug: string };
}) {
  const service = await getService(slug, locale);
  if (!service) return {};
  return buildMetadata({
    locale,
    path: `/services/${slug}`,
    title: service.t.seoTitle ?? service.t.title,
    description: service.t.seoDescription ?? service.t.summary,
    image: service.heroImage ?? undefined
  });
}

export default async function ServiceDetailPage({
  params: { locale, slug }
}: {
  params: { locale: Locale; slug: string };
}) {
  const t = await getTranslations({ locale, namespace: 'nav' });
  const service = await getService(slug, locale);
  if (!service) notFound();

  const process = Array.isArray(service.t.process) ? (service.t.process as any[]) : [];

  return (
    <>
      <JsonLd
        data={breadcrumbSchema([
          { name: t('services'), url: `${SITE_URL}/${locale}/services` },
          { name: service.t.title, url: `${SITE_URL}/${locale}/services/${slug}` }
        ])}
      />
      {service.heroImage && (
        <div className="relative h-64 w-full sm:h-96">
          <Image src={service.heroImage} alt={service.t.title} fill className="object-cover" />
        </div>
      )}
      <Container className="py-16">
        <Reveal variant="up">
          <h1 className="font-display text-3xl font-semibold sm:text-4xl">{service.t.title}</h1>
        </Reveal>
        <Reveal variant="up" delay={80}>
          <p className="mt-4 max-w-2xl text-lg text-graphite-900/70">{service.t.summary}</p>
        </Reveal>

        <Reveal variant="up" delay={140}>
          <div className="prose prose-graphite mt-10 max-w-2xl whitespace-pre-line text-graphite-900/80">
            {service.t.description}
          </div>
        </Reveal>

        {service.t.benefits.length > 0 && (
          <ul className="mt-10 grid gap-3 sm:grid-cols-2">
            {service.t.benefits.map((b, i) => (
              <Reveal key={b} as="li" variant="up" delay={(i % 2) * 80}>
                <div className="rounded-xl bg-graphite-900/5 px-4 py-3 text-sm">{b}</div>
              </Reveal>
            ))}
          </ul>
        )}

        {process.length > 0 && (
          <div className="mt-10">
            <ol className="grid gap-6 sm:grid-cols-3">
              {process.map((step, i) => (
                <li key={i}>
                  <span className="font-display text-2xl text-copper-500/70">
                    {String(i + 1).padStart(2, '0')}
                  </span>
                  <p className="mt-1 font-semibold">{step.title}</p>
                  <p className="text-sm text-graphite-900/60">{step.description}</p>
                </li>
              ))}
            </ol>
          </div>
        )}

        {service.faqs.length > 0 && (
          <div className="mt-14">
            <h2 className="font-display text-xl font-semibold">FAQ</h2>
            <div className="mt-4 divide-y divide-graphite-800/10">
              {service.faqs
                .filter((f) => f.translations[0])
                .map((f) => (
                  <details key={f.id} className="py-4">
                    <summary className="cursor-pointer font-medium">
                      {f.translations[0].question}
                    </summary>
                    <p className="mt-2 text-sm text-graphite-900/60">{f.translations[0].answer}</p>
                  </details>
                ))}
            </div>
          </div>
        )}

        <div className="mt-14">
          <Button href={`/${locale}/devis`}>
            {locale === 'ar' ? 'اطلب عرض سعر' : 'Demander un devis'}
          </Button>
        </div>
      </Container>
    </>
  );
}
