import { notFound } from 'next/navigation';
import { Container, Badge, Heading } from '@/components/ui';
import { setRequestLocale } from 'next-intl/server';
import { Metadata } from 'next';
import { getReferenceBySlug, getAllReferences } from '@/lib/references';
import { MDXRemote } from 'next-mdx-remote/rsc';
import { SITE_URL } from '@/lib/schema';
import TrackedLink from '@/components/analytics/TrackedLink';
import { getButtonClasses, ButtonOverlay } from '@/components/ui/Button';
import { MapPin, Calendar, Briefcase, ChevronLeft } from 'lucide-react';
import Image from 'next/image';

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

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { locale, slug } = await params;
  if (locale !== 'de' && locale !== 'en') return {};

  const reference = await getReferenceBySlug(slug, locale);
  if (!reference) return {};

  return {
    title: `${reference.frontmatter.title} | Referenzen | E-TIB Gruppe`,
    description: `Details zum Projekt ${reference.frontmatter.title} in ${reference.frontmatter.location}.`,
    alternates: {
      canonical: `${SITE_URL}/${locale}/referenzen/${slug}`,
    },
    openGraph: {
      title: `${reference.frontmatter.title} | E-TIB`,
      description: `Details zum Projekt ${reference.frontmatter.title} in ${reference.frontmatter.location}.`,
      url: `${SITE_URL}/${locale}/referenzen/${slug}`,
    },
  };
}

export async function generateStaticParams({ params }: { params: { locale: string } }) {
  const references = await getAllReferences(params.locale);
  return references.map((ref) => ({
    slug: ref.slug,
  }));
}

export default async function ReferenceDetail(props: { params: Promise<{ locale: string; slug: string }> }) {
  const { locale, slug } = await props.params;
  
  if (locale !== 'de' && locale !== 'en') {
    notFound();
  }
  
  setRequestLocale(locale);
  const reference = await getReferenceBySlug(slug, locale);

  if (!reference) {
    notFound();
  }

  // MDX components mapping can be expanded if we use custom components in reference MDX
  const mdxComponents = {
    ul: ({ children }: any) => <ul className="space-y-4 my-8 pl-0 list-none">{children}</ul>,
    li: ({ children }: any) => (
      <li className="flex items-start gap-4 p-4 bg-neutral-50 rounded-2xl border border-neutral-100 shadow-sm">
        <div className="w-6 h-6 rounded-full bg-primary/20 flex items-center justify-center shrink-0 mt-0.5">
          <div className="w-2.5 h-2.5 rounded-full bg-primary" />
        </div>
        <span className="text-lg font-medium text-neutral-800">{children}</span>
      </li>
    ),
  };

  return (
    <div className="flex flex-col min-h-screen bg-white">
      {/* Hero Section */}
      <section className="bg-[#050B14] text-white py-20 md:py-32 relative overflow-hidden">
        {reference.frontmatter.featuredImage && (
          <div className="absolute inset-0 z-0">
            <Image
              src={reference.frontmatter.featuredImage}
              alt={reference.frontmatter.title}
              fill
              className="object-cover opacity-25 mix-blend-luminosity scale-105"
              priority
            />
            <div className="absolute inset-0 bg-gradient-to-t from-[#050B14] via-[#050B14]/60 to-transparent" />
            <div className="absolute inset-0 bg-gradient-to-r from-[#050B14] via-transparent to-transparent" />
          </div>
        )}
        <div className="absolute inset-0 opacity-20 z-0">
          <div className="absolute top-0 left-0 w-full h-full bg-[radial-gradient(circle_at_center,_var(--tw-gradient-stops))] from-primary/30 via-transparent to-transparent" />
        </div>
        <Container className="relative z-10">
          <div className="mb-12">
            <TrackedLink
              href={`/${locale}/referenzen`}
              className="inline-flex items-center gap-2 text-white/60 hover:text-white transition-colors"
              eventProperties={{ location: 'reference_back_btn' }}
            >
              <ChevronLeft className="w-5 h-5" />
              Zurück zur Übersicht
            </TrackedLink>
          </div>
          <div className="max-w-4xl">
            <Badge variant="accent" className="mb-4 md:mb-6">
              Projektreferenz
            </Badge>
            <Heading level={1} variant="white" className="mb-8 leading-tight">
              {reference.frontmatter.title}
            </Heading>
            
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mt-12">
              <div className="flex items-start gap-4 p-6 bg-white/5 rounded-2xl border border-white/10 backdrop-blur-sm">
                <MapPin className="w-8 h-8 text-primary shrink-0" />
                <div>
                  <p className="text-sm text-white/50 mb-1 uppercase tracking-wider font-bold">Ort</p>
                  <p className="font-semibold text-lg">{reference.frontmatter.location}</p>
                </div>
              </div>
              <div className="flex items-start gap-4 p-6 bg-white/5 rounded-2xl border border-white/10 backdrop-blur-sm">
                <Briefcase className="w-8 h-8 text-primary shrink-0" />
                <div>
                  <p className="text-sm text-white/50 mb-1 uppercase tracking-wider font-bold">Auftraggeber</p>
                  <p className="font-semibold text-lg">{reference.frontmatter.client}</p>
                </div>
              </div>
              <div className="flex items-start gap-4 p-6 bg-white/5 rounded-2xl border border-white/10 backdrop-blur-sm">
                <Calendar className="w-8 h-8 text-primary shrink-0" />
                <div>
                  <p className="text-sm text-white/50 mb-1 uppercase tracking-wider font-bold">Zeitraum</p>
                  <p className="font-semibold text-lg">{reference.frontmatter.dateString || new Date(reference.frontmatter.date).getFullYear()}</p>
                </div>
              </div>
            </div>
          </div>
        </Container>
      </section>

      {/* Main Content Area */}
      <Container className="py-16 md:py-24">
        <div className="max-w-4xl mx-auto">
          <h2 className="text-3xl font-bold text-neutral-dark mb-8">Leistungsumfang & Projektbeschreibung</h2>
          
          <div className="prose prose-lg md:prose-xl max-w-none prose-headings:font-bold prose-headings:text-text-primary prose-p:text-text-secondary">
            <MDXRemote source={reference.content} components={mdxComponents} />
          </div>

          <div className="mt-20 flex justify-center">
             <TrackedLink
                href={`/${locale}/referenzen`}
                className={getButtonClasses('primary', 'lg')}
                eventProperties={{ location: 'reference_bottom_back_btn' }}
              >
                <span className="relative z-10 flex items-center justify-center gap-2">
                  Alle Referenzen ansehen
                </span>
                <ButtonOverlay variant="primary" />
              </TrackedLink>
          </div>
        </div>
      </Container>
    </div>
  );
}
