import type { Metadata } from "next";
import Link from "next/link";
import Image from "next/image";
import { notFound } from "next/navigation";
import { ArrowRight, Check } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";
import {
  BUSINESS_EMAIL,
  BUSINESS_HOURS,
  BUSINESS_HOURS_HUMAN,
  BUSINESS_NAME,
  BUSINESS_PHONE,
  CITY_PAGES,
  getCityPage,
  getCityPageTitle,
  type CityPage,
} from "@/lib/city-pages";
import { effectivePrice, getPublicProducts, resolvePublicMediaUrl } from "@/lib/public-product";
import { DEFAULT_OG_IMAGE } from "@/lib/site-og-image";

const SITE_URL = (process.env.NEXT_PUBLIC_SITE_URL || "https://nizamify.com").replace(/\/$/, "");

/** Only the known cities are valid — any other slug returns a real 404 (not a soft 404). */
export const dynamicParams = false;

export function generateStaticParams() {
  return CITY_PAGES.map((c) => ({ city: c.slug }));
}

export async function generateMetadata({
  params,
}: {
  params: { city: string };
}): Promise<Metadata> {
  const city = getCityPage(params.city);
  if (!city) {
    return { title: "Page Not Found", robots: { index: false, follow: false } };
  }
  const title = getCityPageTitle(city);
  const canonical = `/smart-home-automation/${city.slug}`;
  return {
    title,
    description: city.tagline,
    keywords: [
      `smart home ${city.name}`,
      `smart plug ${city.name}`,
      `home automation ${city.name}`,
      ...(city.homeBase
        ? [
            `home automation company ${city.name}`,
            `smart home automation company ${city.name}`,
            `smart home installation ${city.name}`,
          ]
        : []),
      "wifi smart plug",
      "nizamify",
    ],
    alternates: { canonical },
    openGraph: {
      title: `${title} | Nizamify`,
      description: city.tagline,
      url: `${SITE_URL}${canonical}`,
      type: "website",
      images: [{ url: DEFAULT_OG_IMAGE }],
    },
    twitter: {
      card: "summary_large_image",
      title: `${title} | Nizamify`,
      description: city.tagline,
      images: [DEFAULT_OG_IMAGE],
    },
  };
}

function buildSchemas(city: CityPage) {
  const pageUrl = `${SITE_URL}/smart-home-automation/${city.slug}`;

  // Home-base cities get a LocalBusiness; delivery-only cities get a Service
  // with areaServed — we never claim a physical address we don't have.
  const primary = city.homeBase
    ? {
        "@context": "https://schema.org",
        "@type": "LocalBusiness",
        name: `${BUSINESS_NAME} — Smart Home Automation ${city.name}`,
        url: pageUrl,
        telephone: BUSINESS_PHONE,
        email: BUSINESS_EMAIL,
        priceRange: "$$",
        openingHours: BUSINESS_HOURS,
        address: {
          "@type": "PostalAddress",
          ...(city.streetAddress ? { streetAddress: city.streetAddress } : {}),
          addressLocality: city.name,
          addressRegion: city.region,
          ...(city.postalCode ? { postalCode: city.postalCode } : {}),
          addressCountry: "PK",
        },
        ...(city.latitude != null && city.longitude != null
          ? {
              geo: {
                "@type": "GeoCoordinates",
                latitude: city.latitude,
                longitude: city.longitude,
              },
            }
          : {}),
        areaServed: { "@type": "City", name: city.name },
      }
    : {
        "@context": "https://schema.org",
        "@type": "Service",
        serviceType: "Smart Home Automation",
        provider: { "@type": "Organization", name: BUSINESS_NAME, url: SITE_URL },
        areaServed: { "@type": "City", name: city.name },
        url: pageUrl,
      };

  const breadcrumb = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: [
      { "@type": "ListItem", position: 1, name: "Home", item: `${SITE_URL}/` },
      {
        "@type": "ListItem",
        position: 2,
        name: getCityPageTitle(city),
        item: pageUrl,
      },
    ],
  };

  const faq = {
    "@context": "https://schema.org",
    "@type": "FAQPage",
    mainEntity: buildCityFaqs(city).map((f) => ({
      "@type": "Question",
      name: f.question,
      acceptedAnswer: { "@type": "Answer", text: f.answer },
    })),
  };

  return [primary, breadcrumb, faq];
}

function buildCityFaqs(city: CityPage) {
  return [
    {
      question: `Is Nizamify based in ${city.name}?`,
      answer: city.homeBase
        ? `Yes — Nizamify is physically based in the twin cities of Rawalpindi and Islamabad, so ${city.name} orders get fast local delivery and hands-on support, not a faceless marketplace seller.`
        : `Nizamify is based in Rawalpindi & Islamabad and delivers smart home devices to ${city.name} with cash on delivery and WhatsApp support.`,
    },
    {
      question: `What smart home automation services does Nizamify offer in ${city.name}?`,
      answer: `We supply WiFi smart plugs, switches, sensors, and cameras that connect to the Tuya/Smart Life app, Alexa, and Google Assistant — everything you need to automate lighting, appliances, and security in ${city.name}.`,
    },
    {
      question: `Do you offer smart home installation in ${city.name}?`,
      answer: city.homeBase
        ? `Professional installation is launching soon, starting in Rawalpindi and Islamabad — see our Hardware Installations service for details. In the meantime, every product ships with self-install setup steps and WhatsApp support.`
        : `Installation isn't available in ${city.name} yet — it's launching first in Rawalpindi and Islamabad. Every product we ship includes setup steps and WhatsApp support for self-installation.`,
    },
    {
      question: `Can I get custom automation software for my ${city.name} business?`,
      answer: `Yes — beyond smart-home devices, Nizamify builds custom business and process automation software. Learn more about our Custom Software Solutions service.`,
    },
  ];
}

export default async function CityLandingPage({ params }: { params: { city: string } }) {
  const city = getCityPage(params.city);
  if (!city) notFound();

  const products = await getPublicProducts({ limit: 3 });
  const schemas = buildSchemas(city);

  return (
    <div className="flex flex-col">
      {schemas.map((schema, i) => (
        <script
          key={i}
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
        />
      ))}

      {/* Hero */}
      <section className="w-full bg-primary text-white">
        <div className="container my-12 max-w-3xl space-y-5 text-center">
          <h1 className="text-3xl font-bold leading-tight md:text-4xl lg:text-5xl">
            {getCityPageTitle(city)}
          </h1>
          <p className="text-white/90">{city.tagline}</p>
          <div className="flex flex-wrap items-center justify-center gap-3">
            <Button asChild variant="secondary">
              <Link href="/products">Explore Products</Link>
            </Button>
            <Button asChild variant="outline" className="bg-transparent text-white">
              <Link href="/contact-us">Contact Us</Link>
            </Button>
          </div>
        </div>
      </section>

      {/* Intro */}
      <section className="w-full">
        <div className="container my-10 max-w-3xl space-y-4 text-slate-700">
          <p className="text-lg">{city.intro}</p>
        </div>
      </section>

      {/* What you can automate */}
      <section className="w-full bg-slate-50">
        <div className="container my-0 py-10">
          <h2 className="mb-6 text-2xl font-bold text-slate-900 md:text-3xl">
            What you can automate in {city.name}
          </h2>
          <ul className="grid gap-4 sm:grid-cols-2">
            {[
              "Control water pumps, geysers, heaters, and chargers from your phone with a WiFi smart plug.",
              "Make existing ceiling lights and fans app-controlled with a smart switch module.",
              "Track real energy usage and cut your bill with an energy-monitoring smart plug.",
              "Add smart sensors and alarms for extra safety and peace of mind.",
            ].map((item) => (
              <li key={item} className="flex gap-3 rounded-lg border bg-white p-4">
                <Check className="mt-0.5 size-5 shrink-0 text-primary" />
                <span className="text-slate-700">{item}</span>
              </li>
            ))}
          </ul>
        </div>
      </section>

      {/* Why local */}
      <section className="w-full">
        <div className="container my-10">
          <h2 className="mb-6 text-2xl font-bold text-slate-900 md:text-3xl">
            {city.homeBase
              ? `Why buy from a company based in the twin cities?`
              : `Why order from Nizamify in ${city.name}?`}
          </h2>
          <ul className="grid gap-4 md:grid-cols-2">
            {[
              ["Fast local delivery", `Quick delivery across ${city.name} and nearby areas.`],
              ["Cash on delivery", "Pay when your order arrives — no prepayment required."],
              ["Real support", "Hands-on setup help on WhatsApp, in your timezone."],
              [
                "Genuine products",
                "Trusted Smart Life / Tuya ecosystem with Alexa and Google Assistant.",
              ],
            ].map(([title, body]) => (
              <li key={title} className="rounded-lg border p-5">
                <h3 className="font-semibold text-slate-900">{title}</h3>
                <p className="mt-1 text-sm text-slate-600">{body}</p>
              </li>
            ))}
          </ul>
        </div>
      </section>

      {/* Areas served */}
      <section className="w-full bg-slate-50">
        <div className="container py-10">
          <h2 className="mb-3 text-2xl font-bold text-slate-900 md:text-3xl">
            Delivering across {city.name}
          </h2>
          <p className="mb-5 text-slate-600">
            We deliver smart home devices to homes and offices across {city.name}, including:
          </p>
          <div className="flex flex-wrap gap-2">
            {city.neighborhoods.map((area) => (
              <span
                key={area}
                className="rounded-full border bg-white px-3 py-1 text-sm text-slate-700"
              >
                {area}
              </span>
            ))}
          </div>
        </div>
      </section>

      {/* Featured products */}
      {products.length > 0 ? (
        <section className="w-full">
          <div className="container my-10 space-y-6">
            <div className="flex items-center justify-between gap-3">
              <h2 className="text-2xl font-bold text-slate-900 md:text-3xl">Popular smart devices</h2>
              <Button asChild variant="outline">
                <Link href="/products">View all</Link>
              </Button>
            </div>
            <ul className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
              {products.map((p) => {
                const img = resolvePublicMediaUrl(p.images?.[0]);
                const price = effectivePrice(p);
                return (
                  <li
                    key={p._id}
                    className="flex flex-col overflow-hidden rounded-lg border bg-white shadow-sm transition hover:shadow-md"
                  >
                    <Link href={`/products/${p.slug}`} className="block">
                      <div className="relative aspect-[4/3] bg-gray-100">
                        {img ? (
                          <Image
                            src={img}
                            alt={p.title}
                            fill
                            className="object-cover"
                            sizes="(max-width: 768px) 100vw, 33vw"
                          />
                        ) : (
                          <div className="flex h-full items-center justify-center text-sm text-gray-400">
                            No image
                          </div>
                        )}
                      </div>
                      <div className="space-y-1 p-4">
                        <h3 className="line-clamp-2 font-semibold text-slate-900">{p.title}</h3>
                        <p className="text-lg font-bold text-primary">{price.toFixed(2)}</p>
                      </div>
                    </Link>
                  </li>
                );
              })}
            </ul>
          </div>
        </section>
      ) : null}

      {/* FAQ */}
      <section className="w-full">
        <div className="container my-10 max-w-3xl">
          <h2 className="mb-6 text-2xl font-bold text-slate-900 md:text-3xl">
            Frequently Asked Questions
          </h2>
          <Accordion type="single" collapsible className="w-full">
            {buildCityFaqs(city).map((faq, i) => (
              <AccordionItem
                key={i}
                value={`city-faq-${i}`}
                className="border-b border-slate-200"
              >
                <AccordionTrigger className="text-left text-base font-semibold text-slate-900 hover:no-underline">
                  {faq.question}
                </AccordionTrigger>
                <AccordionContent className="text-sm leading-relaxed text-slate-600">
                  {i === 3 ? (
                    <>
                      Yes — beyond smart-home devices, Nizamify builds custom business and process
                      automation software. Learn more about our{" "}
                      <Link
                        href="/services/custom-software-solutions"
                        className="font-semibold text-primary hover:underline"
                      >
                        Custom Software Solutions
                      </Link>{" "}
                      service.
                    </>
                  ) : (
                    faq.answer
                  )}
                </AccordionContent>
              </AccordionItem>
            ))}
          </Accordion>
        </div>
      </section>

      {/* CTA */}
      <section className="w-full">
        <div className="container my-10 rounded-2xl bg-primary px-6 py-10 text-center text-white">
          <h2 className="text-2xl font-bold md:text-3xl">
            Make your {city.name} home smarter today
          </h2>
          <p className="mx-auto mt-2 max-w-xl text-white/90">
            Browse our full range or get a quick recommendation. {BUSINESS_HOURS_HUMAN}.
          </p>
          <div className="mt-5 flex flex-wrap items-center justify-center gap-3">
            <Button asChild variant="secondary">
              <Link href="/products">
                Shop Products <ArrowRight className="ml-1 size-4" />
              </Link>
            </Button>
            <Button asChild variant="outline" className="bg-transparent text-white">
              <Link href="/blogs/best-wifi-smart-plugs-in-pakistan">Read the buyer&apos;s guide</Link>
            </Button>
          </div>
        </div>
      </section>
    </div>
  );
}
