import { setRequestLocale } from 'next-intl/server';
import type { Metadata } from 'next';
import Link from 'next/link';
import { ArrowLeft, ArrowRight, MapPin, Brain, Mic, Workflow, Cloud, Code, CheckCircle } from 'lucide-react';
import { notFound } from 'next/navigation';
import { cities, getCityBySlug, getAllCitySlugs } from '@/data/cities';
import { services } from '@/data/services';
import { BreadcrumbJsonLd, ServiceJsonLd, FAQJsonLd } from '@/components/seo';
import { type Locale, locales } from '@/i18n/config';

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

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

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

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { locale, city: citySlug } = await params;
  const city = getCityBySlug(citySlug);

  if (!city) {
    return { title: 'City Not Found' };
  }

  const titles: Record<string, string> = {
    de: `KI Entwickler ${city.name.de} - AI & Automatisierung | Damjan Savić`,
    en: `AI Developer ${city.name.en} - AI & Automation | Damjan Savić`,
    sr: `AI Developer ${city.name.sr} - AI & Automatizacija | Damjan Savić`,
  };

  const descriptions: Record<string, string> = {
    de: `Professionelle KI-Entwicklung und Automatisierung in ${city.name.de}. Voice AI, Prozessautomatisierung, SaaS-Entwicklung. Ihr AI & Automation Specialist für ${city.name.de} und ${city.region}.`,
    en: `Professional AI development and automation in ${city.name.en}. Voice AI, process automation, SaaS development. Your AI & Automation Specialist for ${city.name.en} and ${city.region}.`,
    sr: `Profesionalni AI razvoj i automatizacija u ${city.name.sr}. Voice AI, automatizacija procesa, SaaS razvoj. Vaš AI & Automation Specialist za ${city.name.sr} i ${city.region}.`,
  };

  return {
    title: titles[locale] || titles.de,
    description: descriptions[locale] || descriptions.de,
    keywords: city.keywords[locale as Locale]?.join(', ') || city.keywords.de.join(', '),
    alternates: {
      canonical: `/${locale}/leistungen/standort/${citySlug}`,
      languages: {
        de: `/de/leistungen/standort/${citySlug}`,
        en: `/en/leistungen/standort/${citySlug}`,
        sr: `/sr/leistungen/standort/${citySlug}`,
      },
    },
    openGraph: {
      title: titles[locale] || titles.de,
      description: descriptions[locale] || descriptions.de,
      type: 'website',
    },
  };
}

export default async function CityPage({ params }: Props) {
  const { locale, city: citySlug } = await params;
  setRequestLocale(locale);

  const city = getCityBySlug(citySlug);

  if (!city) {
    notFound();
  }

  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: city.name[locale as Locale], url: `/${locale}/leistungen/standort/${citySlug}` },
  ];

  const faqItems = locale === 'de' ? [
    {
      question: `Bieten Sie Ihre Dienstleistungen auch vor Ort in ${city.name.de} an?`,
      answer: `Ja, ich arbeite mit Unternehmen in ${city.name.de} und Umgebung. Die meisten Projekte wickle ich remote ab, aber persönliche Meetings in ${city.name.de} sind bei Bedarf möglich.`,
    },
    {
      question: `Welche Branchen bedienen Sie in ${city.name.de}?`,
      answer: `Ich arbeite branchenübergreifend mit Startups, mittelständischen Unternehmen und Konzernen in ${city.name.de}. Besonders häufig sind Projekte in den Bereichen E-Commerce, Fintech, Healthcare und B2B-Services.`,
    },
    {
      question: `Wie schnell können Sie mit einem Projekt in ${city.name.de} starten?`,
      answer: 'Je nach aktuellem Projektstand kann ich meist innerhalb von 1-2 Wochen mit neuen Projekten beginnen. Für dringende Anfragen stehe ich auch kurzfristiger zur Verfügung.',
    },
  ] : locale === 'en' ? [
    {
      question: `Do you also offer your services on-site in ${city.name.en}?`,
      answer: `Yes, I work with companies in ${city.name.en} and the surrounding area. Most projects are handled remotely, but in-person meetings in ${city.name.en} are possible if needed.`,
    },
    {
      question: `Which industries do you serve in ${city.name.en}?`,
      answer: `I work across industries with startups, medium-sized companies and corporations in ${city.name.en}. Projects are particularly common in e-commerce, fintech, healthcare and B2B services.`,
    },
    {
      question: `How quickly can you start a project in ${city.name.en}?`,
      answer: 'Depending on my current project status, I can usually start new projects within 1-2 weeks. I am also available at shorter notice for urgent requests.',
    },
  ] : [
    {
      question: `Da li nudite usluge i na licu mesta u ${city.name.sr}?`,
      answer: `Da, radim sa kompanijama u ${city.name.sr} i okolini. Većina projekata se obrađuje remote, ali lični sastanci u ${city.name.sr} su mogući po potrebi.`,
    },
    {
      question: `Koje industrije opslužujete u ${city.name.sr}?`,
      answer: `Radim u svim industrijama sa startapima, srednjim preduzećima i korporacijama u ${city.name.sr}. Projekti su posebno česti u e-commerce, fintech, zdravstvu i B2B uslugama.`,
    },
    {
      question: `Koliko brzo možete započeti projekat u ${city.name.sr}?`,
      answer: 'U zavisnosti od trenutnog statusa projekta, obično mogu započeti nove projekte u roku od 1-2 nedelje. Dostupan sam i u kraćem roku za hitne zahteve.',
    },
  ];

  const pageTitle = locale === 'de'
    ? `KI Entwickler in ${city.name.de}`
    : locale === 'sr'
    ? `AI Developer u ${city.name.sr}`
    : `AI Developer in ${city.name.en}`;

  // Get other cities for internal linking
  const otherCities = cities.filter((c) => c.slug !== citySlug).slice(0, 4);

  return (
    <div className="min-h-screen">
      <BreadcrumbJsonLd items={breadcrumbItems} locale={locale as Locale} />
      <ServiceJsonLd
        name={pageTitle}
        description={city.description[locale as Locale]}
        url={`/${locale}/leistungen/standort/${citySlug}`}
        locale={locale as Locale}
        areaServed={[city.name.de, ...city.nearbyAreas]}
      />
      <FAQJsonLd items={faqItems} 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-2 text-zinc-400 mb-4">
            <MapPin className="h-5 w-5" />
            <span>{city.region}, Deutschland</span>
          </div>

          <h1 className="text-4xl md:text-5xl font-bold text-white mb-6">
            {pageTitle}
          </h1>

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

          {/* Keywords as tags */}
          <div className="flex flex-wrap gap-2">
            {city.keywords[locale as Locale]?.slice(0, 5).map((keyword) => (
              <span
                key={keyword}
                className="px-3 py-1 bg-zinc-800/50 border border-zinc-700 text-sm text-zinc-300 rounded-full"
              >
                {keyword}
              </span>
            ))}
          </div>
        </div>
      </section>

      {/* Services 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'
              ? `Meine Leistungen in ${city.name.de}`
              : locale === 'sr'
              ? `Moje usluge u ${city.name.sr}`
              : `My services in ${city.name.en}`}
          </h2>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {services.map((service) => {
              const IconComponent = iconMap[service.icon] || Brain;
              return (
                <Link
                  key={service.slug}
                  href={`/${locale}/leistungen/${service.slug}`}
                  className="group flex items-start gap-4 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">
                    <IconComponent className="h-5 w-5 text-zinc-400 group-hover:text-white transition-colors" />
                  </div>
                  <div>
                    <h3 className="text-lg font-semibold text-white mb-1">
                      {service.name[locale as Locale]}
                    </h3>
                    <p className="text-sm text-zinc-400">
                      {service.shortDescription[locale as Locale]}
                    </p>
                  </div>
                </Link>
              );
            })}
          </div>
        </div>
      </section>

      {/* Why Choose Me 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'
              ? `Warum mit mir arbeiten in ${city.name.de}?`
              : locale === 'sr'
              ? `Zašto raditi sa mnom u ${city.name.sr}?`
              : `Why work with me in ${city.name.en}?`}
          </h2>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {(locale === 'de'
              ? [
                  'Über 7 Jahre Erfahrung in der Softwareentwicklung',
                  'Spezialisiert auf KI und Automatisierung',
                  'Remote-Arbeit mit persönlichen Meetings möglich',
                  'Klare Kommunikation auf Deutsch und Englisch',
                  'Flexible Zusammenarbeit und transparente Preise',
                  'Nachweisbare Erfolge in ähnlichen Projekten',
                ]
              : locale === 'en'
              ? [
                  'Over 7 years of software development experience',
                  'Specialized in AI and automation',
                  'Remote work with in-person meetings possible',
                  'Clear communication in German and English',
                  'Flexible collaboration and transparent pricing',
                  'Proven success in similar projects',
                ]
              : [
                  'Preko 7 godina iskustva u razvoju softvera',
                  'Specijalizovan za AI i automatizaciju',
                  'Remote rad sa mogućnošću ličnih sastanaka',
                  'Jasna komunikacija na nemačkom i engleskom',
                  'Fleksibilna saradnja i transparentne cene',
                  'Dokazani uspesi u sličnim projektima',
                ]
            ).map((point, 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">{point}</span>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Nearby Areas */}
      <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-4">
            {locale === 'de'
              ? 'Auch verfügbar in der Region'
              : locale === 'sr'
              ? 'Takođe dostupno u regionu'
              : 'Also available in the region'}
          </h2>
          <p className="text-zinc-400 mb-6">
            {locale === 'de'
              ? `Neben ${city.name.de} arbeite ich auch mit Unternehmen in:`
              : locale === 'sr'
              ? `Pored ${city.name.sr}, radim i sa kompanijama u:`
              : `In addition to ${city.name.en}, I also work with companies in:`}
          </p>
          <div className="flex flex-wrap gap-2">
            {city.nearbyAreas.map((area) => (
              <span
                key={area}
                className="px-4 py-2 bg-zinc-800/50 border border-zinc-700 text-zinc-300 rounded-lg"
              >
                {area}
              </span>
            ))}
          </div>
        </div>
      </section>

      {/* Other Cities */}
      <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' ? 'Weitere Standorte' : locale === 'sr' ? 'Ostale lokacije' : 'Other Locations'}
          </h2>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {otherCities.map((otherCity) => (
              <Link
                key={otherCity.slug}
                href={`/${locale}/leistungen/standort/${otherCity.slug}`}
                className="group flex items-center gap-2 p-4 bg-zinc-800/30 border border-zinc-800 rounded-lg hover:border-zinc-700 transition-all duration-300"
              >
                <MapPin className="h-4 w-4 text-zinc-500 group-hover:text-white transition-colors" />
                <span className="text-zinc-300 group-hover:text-white transition-colors">
                  {otherCity.name[locale as Locale]}
                </span>
              </Link>
            ))}
          </div>
        </div>
      </section>

      {/* FAQ Section */}
      <section className="py-16 bg-zinc-800/20">
        <div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8">
          <h2 className="text-2xl font-bold text-white text-center mb-8">
            {locale === 'de'
              ? `Häufige Fragen für ${city.name.de}`
              : locale === 'sr'
              ? `Česta pitanja za ${city.name.sr}`
              : `FAQ for ${city.name.en}`}
          </h2>
          <div className="space-y-4">
            {faqItems.map((item, index) => (
              <div
                key={index}
                className="bg-zinc-800/30 border border-zinc-800 rounded-lg p-6"
              >
                <h3 className="text-lg font-semibold text-white mb-2">
                  {item.question}
                </h3>
                <p className="text-zinc-400">{item.answer}</p>
              </div>
            ))}
          </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'
              ? `Projekt in ${city.name.de} starten?`
              : locale === 'sr'
              ? `Započnite projekat u ${city.name.sr}?`
              : `Start a project in ${city.name.en}?`}
          </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' ? 'Kontakt aufnehmen' : locale === 'sr' ? 'Kontaktirajte me' : 'Get in touch'}
            <ArrowRight className="h-5 w-5 ml-2" />
          </Link>
        </div>
      </section>
    </div>
  );
}
