import { Button } from "@/components/ui/button";
import { ArrowRight, Check } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import type { Metadata } from "next";
import heroImage from "@/assets/images/home/static.webp";
import madamImage from "@/assets/images/home/all-app.webp";
import inventoryBackground from "@/assets/icons/inventory-background.svg";
import shippingLabelBackground from "@/assets/icons/shipping-label-background.svg";
import shippingLabelImage from "@/assets/images/home/shippping-label.webp";
import productManagementImage from "@/assets/images/home/prodcut-management.webp";
import desktopScreen from "@/assets/icons/desktop.svg";
import { effectivePrice, getPublicProducts, resolvePublicMediaUrl } from "@/lib/public-product";
import { getPublicPageSeo } from "@/lib/public-page-seo";
import { resolveOgImageUrl } from "@/lib/site-og-image";
import AddToCartButton from "@/components/shop/add-to-cart-button";
import ProductShippingBadges from "@/components/shop/product-shipping-badges";
import HomeHeroWhatsAppButton from "@/components/shop/home-hero-whatsapp-button";
import SectionWhatsAppCta from "@/components/shop/section-whatsapp-cta";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";

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

const homeFaqs = [
  {
    question: "What is Nizamify?",
    answer:
      "Nizamify is a Rawalpindi & Islamabad based smart home and business automation company. We sell smart WiFi plugs, switches, cameras, and other connected devices, plus a unified app to control and automate them.",
  },
  {
    question: "Do you deliver across Pakistan?",
    answer: "Yes. We ship nationwide, with fast local delivery in Rawalpindi and Islamabad.",
  },
  {
    question: "Can I order or ask questions on WhatsApp?",
    answer:
      "Yes — every product page has a WhatsApp button that opens a pre-filled message with the product name, price, and link, so you can order or ask questions directly.",
  },
  {
    question: "Do you offer installation support?",
    answer: "Installation support depends on the product and your location. Contact us with your city and product to confirm.",
  },
  {
    question: "Can businesses use Nizamify too?",
    answer:
      "Yes. Beyond smart-home devices, Nizamify also builds business automation dashboards, device workflows, and monitoring systems for offices and small businesses.",
  },
];

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

export async function generateMetadata(): Promise<Metadata> {
  const seo = await getPublicPageSeo("home");
  const title = seo?.metaTitle?.trim() || seo?.title?.trim() || "Smart Home & Business Automation";
  const description =
    seo?.metaDescription?.trim() ||
    "Transform your home and business with intelligent automation, connected devices, and centralized control.";
  const canonical = "/";
  const keywords = Array.isArray(seo?.metaKeywords) && seo.metaKeywords.length > 0
    ? seo.metaKeywords
    : ["Nizamify", "home automation", "smart business", "iot"];
  const image = resolveOgImageUrl(seo?.image);

  return {
    title,
    description,
    keywords,
    alternates: { canonical },
    openGraph: {
      title,
      description,
      url: `${SITE_URL}${canonical}`,
      type: "website",
      images: [{ url: image }],
    },
    twitter: {
      card: "summary_large_image",
      title,
      description,
      images: [image],
    },
  };
}

export default async function HomePage() {
  const products = await getPublicProducts({ limit: 3 });

  return (
    <div className="flex min-h-[70vh] flex-col">
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(homeFaqSchema) }}
      />
      <section className="w-full bg-primary">
        <div className="container my-10 grid items-center gap-8 lg:grid-cols-2">
          <div className="flex flex-col gap-5 text-center text-white lg:text-left">
            <h1 className="font-bold leading-tight text-[clamp(1.35rem,3.2vw,2.6rem)] md:text-[clamp(1.5rem,2.9vw,2.9rem)]">
              <span className="block whitespace-nowrap">
                Transform Your <span className="text-secondary">Home</span> &{" "}
                <span className="text-secondary">Business</span>
              </span>
              <span className="block whitespace-nowrap">with Smart Automation</span>
            </h1>
            <p>
              Seamlessly control and optimize your environment with cutting-edge smart solutions. From intelligent home systems to advanced business automation, Nizamify delivers a centralized platform to enhance efficiency, security, and convenience—all in one place.
            </p>
            <div className="flex flex-wrap items-center justify-center gap-x-2 gap-y-2 lg:justify-start">
              <Link href="/products">
                <Button variant="secondary">Explore Products</Button>
              </Link>
              <HomeHeroWhatsAppButton />
            </div>
          </div>
          <div className="text-center lg:text-right">
            <div className="mx-auto w-full max-w-[360px] overflow-hidden rounded-2xl sm:max-w-[420px] lg:ml-auto lg:mr-0">
              <Image src={heroImage} className="w-full" alt="Nizamify smart home and business automation devices" width={1000} height={1000} />
            </div>
          </div>
        </div>
      </section>
      <section className="w-full">
        <div className="container my-10 space-y-6">
          <div className="flex items-center justify-between gap-3">
            <div>
              <h2 className="text-2xl font-bold text-slate-900 md:text-3xl">Products</h2>
              <p className="mt-1 text-sm text-gray-600">Explore some of our latest smart products.</p>
            </div>
            <Button asChild variant="outline">
              <Link href="/products">View all</Link>
            </Button>
          </div>

          {products.length === 0 ? (
            <div className="rounded-lg border bg-white p-8 text-center text-gray-500">
              No products available right now.
            </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);
                const showStrike = p.salePrice != null && p.salePrice >= 0;
                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">
                          <span className="font-bold text-primary">{price.toFixed(2)}</span>
                          {showStrike ? (
                            <span className="ml-2 text-sm text-gray-400 line-through">
                              {p.price.toFixed(2)}
                            </span>
                          ) : null}
                        </p>
                        <ProductShippingBadges
                          shippingCost={p.shippingCost}
                          freeShipping={p.freeShipping}
                          expressShipping={p.expressShipping}
                        />
                      </div>
                    </Link>
                    <div className="mt-auto p-4 pt-0">
                      <AddToCartButton product={p} />
                    </div>
                  </li>
                );
              })}
            </ul>
          )}
        </div>
      </section>
      <section className="w-full">
        <div className="container my-10 flex flex-wrap items-center">
          <div className="flex flex-col gap-5 text-center md:basis-1/2 md:text-left">
            <span className="text-xs font-semibold uppercase tracking-wider text-secondary">
              Platform
            </span>
            <h2 className="text-3xl font-bold text-primary lg:text-5xl">
              An all-in-one app that makes it smarter
            </h2>
            <div className="leading-loose text-black">
              <ul className="space-y-2">
                <li className="flex gap-2">
                  <Check className="mt-1 size-4 shrink-0" />
                  Unified Control: Effortlessly manage your connected hardware with a user-friendly
                  interface
                </li>
                <li className="flex gap-2">
                  <Check className="mt-1 size-4 shrink-0" />
                  Instant Automation: Save time and increase efficiency with streamlined device
                  routines
                </li>
                <li className="flex gap-2">
                  <Check className="mt-1 size-4 shrink-0" />
                  Remote Access: Monitor your infrastructure on the go with our responsive mobile
                  design
                </li>
              </ul>
            </div>
            <SectionWhatsAppCta topic="Nizamify features and the all-in-one smart app">
              Explore Features
              <ArrowRight className="size-6" />
            </SectionWhatsAppCta>
          </div>
          <div className="text-center md:basis-1/2">
            <div className="mx-auto w-11/12 overflow-hidden rounded-2xl shadow-lg">
              <Image src={madamImage} className="w-full" alt="Nizamify all-in-one smart control app" width={1000} height={1000} />
            </div>
          </div>
        </div>
      </section>
      {/* <section className="relative w-full overflow-hidden">
        <Image
          src={inventoryBackground}
          className="absolute left-0 top-0 min-h-full min-w-full object-cover"
          alt=""
          width={100}
          height={100}
        />
        <div className="relative my-8 flex w-full items-center">
          <div className="container my-10 flex flex-wrap">
            <div className="flex flex-col gap-3 text-center">
              <h1 className="text-3xl font-bold text-primary lg:text-5xl">
                Simplified Inventory Management
              </h1>
              <p className="text-gray-500">
                Effortlessly manage your inventory and maintain your stock level. Our ecommerce
                management system provides a centralized hub for the seamless management of the
                products from suppliers to the sellers.
              </p>
              <Image
                src={desktopScreen}
                className="mx-auto w-full"
                alt=""
                width={1000}
                height={1000}
              />
            </div>
          </div>
        </div>
      </section> */}

      <section className="relative w-full overflow-hidden">
        <Image
          src={shippingLabelBackground}
          className="absolute left-0 top-0 min-h-full min-w-full object-cover"
          alt=""
          width={100}
          height={100}
        />
        <div className="relative flex w-full items-center py-6 md:py-10">
          <div className="container flex flex-wrap items-center gap-6 md:gap-0">
            <div className="flex flex-col gap-4 text-center text-white md:basis-1/2 md:pr-6 md:text-left">
              <span className="text-xs font-semibold uppercase tracking-wider text-secondary">
                Automation
              </span>
              <h2 className="text-3xl font-bold leading-tight text-white lg:text-5xl">
                Effortless Smart Device Orchestration
              </h2>
              <p className="text-white/90">
                Configure carrier-grade smart automation in a few clicks. Connect appliances,
                schedule tasks in bulk, and monitor every device from one place—fewer manual
                inputs and faster response.
              </p>
              <SectionWhatsAppCta
                topic="smart device orchestration and automations"
                className="gap-1 px-0 text-white hover:text-white/90"
              >
                Generate Automations
                <ArrowRight className="size-6" />
              </SectionWhatsAppCta>
            </div>
            <div className="text-center md:basis-1/2">
              <Image
                src={shippingLabelImage}
                className="mx-auto h-auto w-full max-w-[620px] max-h-[280px] object-contain md:max-h-[340px]"
                alt=""
                width={1000}
                height={1000}
              />
            </div>
          </div>
        </div>
      </section>
      <section className="w-full">
        <div className="container my-10 flex flex-wrap items-center">
          <div className="text-center md:basis-1/2">
            <div className="mx-auto w-11/12 overflow-hidden rounded-2xl shadow-lg">
              <Image
                src={productManagementImage}
                className="w-full"
                alt=""
                width={1000}
                height={1000}
              />
            </div>
          </div>
          <div className="flex flex-col gap-5 text-center md:basis-1/2 md:text-left md:pl-10 pl-0">
            <span className="text-xs font-semibold uppercase tracking-wider text-secondary">
              Integration
            </span>
            <h2 className="text-3xl font-bold text-primary lg:text-5xl">
              Optimize Smart Integration
            </h2>

            <p className="text-black">
              Design seamless automation ecosystems with smart controls, hardware, and sensors.
              Sync devices, monitor performance, and manage your entire infrastructure from one
              unified digital dashboard.
            </p>
            <SectionWhatsAppCta topic="smart integration and system features" className="px-0">
              Explore System Features <ArrowRight className="size-6" />
            </SectionWhatsAppCta>
          </div>

        </div>
      </section>
      <section className="w-full bg-slate-50">
        <div className="container my-10">
          <div className="mx-auto max-w-3xl text-center">
            <span className="text-xs font-semibold uppercase tracking-wider text-secondary">
              Support
            </span>
            <h2 className="mt-2 text-3xl font-bold text-primary lg:text-4xl">
              Frequently Asked Questions
            </h2>
            <p className="mt-2 text-sm text-gray-600">
              Quick answers before you buy. For more, see the full{" "}
              <Link href="/faqs" className="font-medium text-primary hover:underline">
                FAQs page
              </Link>
              .
            </p>
          </div>
          <div className="mx-auto mt-8 max-w-3xl">
            <Accordion type="single" collapsible className="w-full">
              {homeFaqs.map((faq, i) => (
                <AccordionItem key={i} value={`home-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">
                    {faq.answer}
                  </AccordionContent>
                </AccordionItem>
              ))}
            </Accordion>
          </div>
        </div>
      </section>
    </div>
  );
}
