import { setRequestLocale } from 'next-intl/server';
import type { Metadata } from 'next';
import Link from 'next/link';
import { ArrowLeft, ArrowRight, CheckCircle, Brain, Mic, Workflow, Cloud, Code, Bot, Building, ShoppingCart, Factory } from 'lucide-react';
import { notFound } from 'next/navigation';
import { allServices, getServiceBySlug, getAllServiceSlugs } from '@/data/services';
import { BreadcrumbJsonLd, ServiceJsonLd } from '@/components/seo';
import { type Locale, locales } from '@/i18n/config';

type Props = {
  params: Promise<{ locale: string; slug: string }>;
};

const iconMap: Record<string, React.ComponentType<{ className?: string }>> = {
  Brain,
  Mic,
  Workflow,
  Cloud,
  Code,
  Bot,
  Building,
  ShoppingCart,
  Factory,
};

export async function generateStaticParams() {
  const slugs = getAllServiceSlugs();
  return locales.flatMap((locale) =>
    slugs.map((slug) => ({
      locale,
      slug,
    }))
  );
}

const BASE_URL = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { locale, slug } = await params;
  const service = getServiceBySlug(slug);

  if (!service) {
    return { title: 'Service Not Found' };
  }

  const title = locale === 'de'
    ? `${service.name.de} - Köln & Deutschland | Damjan Savić`
    : locale === 'sr'
    ? `${service.name.sr} - Keln & Nemačka | Damjan Savić`
    : `${service.name.en} | Remote AI Developer for USA, UK & Europe`;

  const localePath = locale === 'de' ? `/leistungen/${slug}` : `/${locale}/leistungen/${slug}`;

  // Enhanced keywords for English
  const enhancedKeywords = locale === 'en'
    ? [...service.technologies, 'Remote AI Developer', 'Hire AI Developer', 'AI Consultant USA', 'AI Developer UK'].join(', ')
    : service.technologies.join(', ');

  return {
    title,
    description: service.description[locale as Locale] || service.description.de,
    keywords: enhancedKeywords,
    alternates: {
      canonical: `${BASE_URL}${localePath}`,
      languages: {
        'x-default': `${BASE_URL}/de/leistungen/${slug}`,
        de: `${BASE_URL}/de/leistungen/${slug}`,
        en: `${BASE_URL}/en/leistungen/${slug}`,
        sr: `${BASE_URL}/sr/leistungen/${slug}`,
      },
    },
    openGraph: {
      title,
      description: service.shortDescription[locale as Locale] || service.shortDescription.de,
      url: `${BASE_URL}${localePath}`,
      type: 'website',
      locale: locale === 'de' ? 'de_DE' : locale === 'sr' ? 'sr_RS' : 'en_US',
      alternateLocale: ['de_DE', 'en_US', 'sr_RS'].filter(l => l !== (locale === 'de' ? 'de_DE' : locale === 'sr' ? 'sr_RS' : 'en_US')),
    },
  };
}

export default async function ServicePage({ params }: Props) {
  const { locale, slug } = await params;
  setRequestLocale(locale);

  const service = getServiceBySlug(slug);

  if (!service) {
    notFound();
  }

  const IconComponent = iconMap[service.icon] || Brain;

  const breadcrumbItems = [
    { name: locale === 'de' ? 'Start' : locale === 'sr' ? 'Početna' : 'Home', url: `/${locale}` },
    { name: locale === 'de' ? 'Leistungen' : locale === 'sr' ? 'Usluge' : 'Services', url: `/${locale}/leistungen` },
    { name: service.name[locale as Locale], url: `/${locale}/leistungen/${slug}` },
  ];

  // Get related services (excluding current)
  const relatedServices = allServices.filter((s) => s.slug !== slug).slice(0, 3);

  return (
    <div className="min-h-screen">
      <BreadcrumbJsonLd items={breadcrumbItems} locale={locale as Locale} />
      <ServiceJsonLd
        name={service.name[locale as Locale]}
        description={service.description[locale as Locale]}
        url={`/${locale}/leistungen/${slug}`}
        locale={locale as Locale}
      />

      {/* Hero Section */}
      <section className="py-24">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
          {/* Back Link */}
          <Link
            href={`/${locale}/leistungen`}
            className="inline-flex items-center gap-2 text-zinc-400 hover:text-white transition-colors mb-8"
          >
            <ArrowLeft className="h-4 w-4" />
            {locale === 'de' ? 'Alle Leistungen' : locale === 'sr' ? 'Sve usluge' : 'All Services'}
          </Link>

          <div className="flex items-center gap-4 mb-6">
            <div className="p-4 bg-zinc-800/50 rounded-xl">
              <IconComponent className="h-8 w-8 text-white" />
            </div>
          </div>

          <h1 className="text-4xl md:text-5xl font-bold text-white mb-6">
            {service.name[locale as Locale]}
          </h1>

          <p className="text-xl text-zinc-400 mb-8">
            {service.description[locale as Locale]}
          </p>

          {/* Technologies */}
          <div className="flex flex-wrap gap-2">
            {service.technologies.map((tech) => (
              <span
                key={tech}
                className="px-3 py-1 bg-zinc-800/50 border border-zinc-700 text-sm text-zinc-300 rounded-full"
              >
                {tech}
              </span>
            ))}
          </div>
        </div>
      </section>

      {/* Features Section */}
      <section className="py-16 bg-zinc-800/20">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
          <h2 className="text-2xl font-bold text-white mb-8">
            {locale === 'de' ? 'Was ich anbiete' : locale === 'sr' ? 'Šta nudim' : 'What I offer'}
          </h2>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {service.features[locale as Locale].map((feature, index) => (
              <div
                key={index}
                className="flex items-start gap-3 p-4 bg-zinc-800/30 rounded-lg"
              >
                <CheckCircle className="h-5 w-5 text-green-500 flex-shrink-0 mt-0.5" />
                <span className="text-zinc-300">{feature}</span>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Use Cases Section */}
      <section className="py-16">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
          <h2 className="text-2xl font-bold text-white mb-8">
            {locale === 'de' ? 'Anwendungsbeispiele' : locale === 'sr' ? 'Primeri primene' : 'Use Cases'}
          </h2>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {service.useCases[locale as Locale].map((useCase, index) => (
              <div
                key={index}
                className="p-6 bg-zinc-800/30 border border-zinc-800 rounded-xl"
              >
                <div className="flex items-center gap-3">
                  <div className="w-8 h-8 bg-zinc-700 rounded-full flex items-center justify-center text-sm font-semibold text-white">
                    {index + 1}
                  </div>
                  <span className="text-zinc-200">{useCase}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Related Services */}
      <section className="py-16 bg-zinc-800/20">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
          <h2 className="text-2xl font-bold text-white mb-8">
            {locale === 'de' ? 'Weitere Leistungen' : locale === 'sr' ? 'Ostale usluge' : 'Other Services'}
          </h2>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            {relatedServices.map((relatedService) => {
              const RelatedIcon = iconMap[relatedService.icon] || Brain;
              return (
                <Link
                  key={relatedService.slug}
                  href={`/${locale}/leistungen/${relatedService.slug}`}
                  className="group p-6 bg-zinc-800/30 border border-zinc-800 rounded-xl hover:border-zinc-700 transition-all duration-300"
                >
                  <div className="p-2 bg-zinc-800/50 rounded-lg w-fit mb-3">
                    <RelatedIcon className="h-5 w-5 text-zinc-400 group-hover:text-white transition-colors" />
                  </div>
                  <h3 className="text-lg font-semibold text-white mb-2">
                    {relatedService.name[locale as Locale]}
                  </h3>
                  <p className="text-sm text-zinc-400">
                    {relatedService.shortDescription[locale as Locale]}
                  </p>
                </Link>
              );
            })}
          </div>
        </div>
      </section>

      {/* CTA Section */}
      <section className="py-24">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
          <h2 className="text-3xl font-bold text-white mb-4">
            {locale === 'de'
              ? `${service.name.de} für Ihr Unternehmen?`
              : locale === 'sr'
              ? `${service.name.sr} za vašu kompaniju?`
              : `${service.name.en} for your business?`}
          </h2>
          <p className="text-zinc-400 mb-8">
            {locale === 'de'
              ? 'Lassen Sie uns besprechen, wie ich Ihnen helfen kann.'
              : locale === 'sr'
              ? 'Razgovarajmo o tome kako vam mogu pomoći.'
              : "Let's discuss how I can help you."}
          </p>
          <Link
            href={`/${locale}/contact`}
            className="inline-flex items-center px-8 py-4 bg-white text-zinc-900 font-semibold rounded-lg hover:bg-zinc-100 transition-colors"
          >
            {locale === 'de' ? 'Projekt besprechen' : locale === 'sr' ? 'Razgovarajte o projektu' : 'Discuss project'}
            <ArrowRight className="h-5 w-5 ml-2" />
          </Link>
        </div>
      </section>
    </div>
  );
}
