import { BlogHeroCover } from "@/components/blog/blog-hero-cover";
import { BlogFaqs } from "@/components/blog/blog-faqs";
import BlogVisitTracker from "@/components/blog/blog-visit-tracker";
import { getPublicBlogBySlug, getPublicBlogs, resolvePublicMediaUrl } from "@/lib/public-blog";
import {
  effectivePrice,
  getPublicProducts,
  resolvePublicMediaUrl as resolveProductMediaUrl,
} from "@/lib/public-product";
import { extractBlogFaqs } from "@/lib/blog-faqs";
import { DEFAULT_OG_IMAGE } from "@/lib/site-og-image";
import ProductShippingBadges from "@/components/shop/product-shipping-badges";
import AddToCartButton from "@/components/shop/add-to-cart-button";
import SectionWhatsAppCta from "@/components/shop/section-whatsapp-cta";
import type { Metadata } from "next";
import { ArrowLeft, ArrowRight, CalendarDays, Sparkles, User } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";

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

function stripHtml(value: string) {
  return value.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
}

export async function generateMetadata({
  params,
}: {
  params: { slug: string };
}): Promise<Metadata> {
  const blog = await getPublicBlogBySlug(params.slug);
  if (!blog) {
    return {
      title: "Blog Not Found",
      robots: {
        index: false,
        follow: false,
      },
    };
  }

  const description =
    blog.excerpt?.trim() || stripHtml(blog.content).slice(0, 180) || "Read this blog post on Nizamify.";
  const canonical = `/blogs/${blog.slug}`;
  const coverAbsolute = resolvePublicMediaUrl(blog.coverImage);

  return {
    title: blog.title,
    description,
    keywords: ["Nizamify blog", blog.title, blog.category?.name || "General"],
    alternates: {
      canonical,
    },
    openGraph: {
      title: blog.title,
      description,
      type: "article",
      url: `${SITE_URL}${canonical}`,
      publishedTime: blog.publishedAt || blog.createdAt,
      authors: [blog.createdBy?.firstName || blog.createdBy?.username || "Nizamify"],
      images: [
        {
          url: coverAbsolute || DEFAULT_OG_IMAGE,
          alt: blog.title,
        },
      ],
    },
    twitter: {
      card: "summary_large_image",
      title: blog.title,
      description,
      images: [coverAbsolute || DEFAULT_OG_IMAGE],
    },
  };
}

export default async function BlogDetailPage({ params }: { params: { slug: string } }) {
  const blog = await getPublicBlogBySlug(params.slug);
  if (!blog) notFound();

  // Fetch related articles + featured products in parallel so the page renders
  // a richer, more engaging experience without extra round-trips.
  const [relatedRaw, products] = await Promise.all([
    getPublicBlogs({ category: blog.category?.slug || undefined, limit: 4 }),
    getPublicProducts({ limit: 3 }),
  ]);
  let related = relatedRaw.filter((b) => b.slug !== blog.slug).slice(0, 3);
  // If the current category has too few siblings, top up with the latest posts.
  if (related.length < 3) {
    const latest = await getPublicBlogs({ limit: 6 });
    const seen = new Set([blog.slug, ...related.map((b) => b.slug)]);
    for (const b of latest) {
      if (related.length >= 3) break;
      if (seen.has(b.slug)) continue;
      related.push(b);
      seen.add(b.slug);
    }
  }

  const authorName =
    [blog.createdBy?.firstName, blog.createdBy?.lastName].filter(Boolean).join(" ").trim() ||
    blog.createdBy?.username ||
    "Admin";
  const coverSrc = resolvePublicMediaUrl(blog.coverImage);
  const publishedLabel = blog.publishedAt
    ? new Date(blog.publishedAt).toLocaleDateString(undefined, {
      year: "numeric",
      month: "long",
      day: "numeric",
    })
    : null;

  const { content: articleHtml, faqs, trailingHtml } = extractBlogFaqs(blog.content);

  const postSchema = {
    "@context": "https://schema.org",
    "@type": "BlogPosting",
    headline: blog.title,
    description: blog.excerpt || stripHtml(blog.content).slice(0, 180),
    image: coverSrc || undefined,
    datePublished: blog.publishedAt || blog.createdAt,
    dateModified: blog.createdAt || blog.publishedAt,
    articleSection: blog.category?.name || "General",
    author: {
      "@type": "Person",
      name: authorName,
    },
    publisher: {
      "@type": "Organization",
      name: "Nizamify",
      url: SITE_URL,
    },
    mainEntityOfPage: `${SITE_URL}/blogs/${blog.slug}`,
  };
  const breadcrumbSchema = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: [
      {
        "@type": "ListItem",
        position: 1,
        name: "Home",
        item: `${SITE_URL}/`,
      },
      {
        "@type": "ListItem",
        position: 2,
        name: "Blogs",
        item: `${SITE_URL}/blogs`,
      },
      {
        "@type": "ListItem",
        position: 3,
        name: blog.title,
        item: `${SITE_URL}/blogs/${blog.slug}`,
      },
    ],
  };
  const faqSchema =
    faqs.length > 0
      ? {
          "@context": "https://schema.org",
          "@type": "FAQPage",
          mainEntity: faqs.map((f) => ({
            "@type": "Question",
            name: f.question,
            acceptedAnswer: { "@type": "Answer", text: f.answerText },
          })),
        }
      : null;

  return (
    <div className="min-h-[80vh] bg-gradient-to-b from-[#F8F9FA] via-white to-white">
      <BlogVisitTracker slug={blog.slug} />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(postSchema) }}
      />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbSchema) }}
      />
      {faqSchema ? (
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(faqSchema) }}
        />
      ) : null}

      <div className="container pt-5">
        <Link
          href="/blogs"
          className="inline-flex items-center gap-2 text-sm font-semibold text-primary transition-colors hover:text-secondary"
        >
          <ArrowLeft className="size-4 shrink-0" aria-hidden />
          Back to blog
        </Link>
      </div>

      {/* Reading column: left-aligned inside the same container width as the site header. */}
      <article className="container min-w-0 pb-4 pt-8 sm:pt-10">
        <div className="max-w-4xl">
          <header>
            <p className="mb-4 inline-flex rounded-full border border-secondary/30 bg-secondary/10 px-3 py-1 text-xs font-bold uppercase tracking-wider text-secondary">
              {blog.category?.name || "General"}
            </p>
            <h1 className="text-balance text-3xl font-bold leading-tight tracking-tight text-primary sm:text-4xl md:text-[2.75rem] md:leading-[1.15]">
              {blog.title}
            </h1>
            {blog.excerpt ? (
              <p className="mt-5 max-w-2xl text-pretty text-base leading-relaxed text-slate-600 sm:text-lg">
                {blog.excerpt}
              </p>
            ) : null}
            <div className="mt-6 flex flex-wrap items-center gap-x-6 gap-y-2 text-sm text-slate-600">
              <span className="inline-flex items-center gap-2">
                <span className="flex size-8 items-center justify-center rounded-full bg-primary/10 text-primary">
                  <User className="size-4" aria-hidden />
                </span>
                <span className="font-medium text-slate-800">{authorName}</span>
              </span>
              {publishedLabel ? (
                <span className="inline-flex items-center gap-2 text-slate-500">
                  <CalendarDays className="size-4 shrink-0 text-secondary" aria-hidden />
                  <time dateTime={blog.publishedAt}>{publishedLabel}</time>
                </span>
              ) : null}
            </div>
          </header>

          {coverSrc ? (
            <div className="mt-10">
              <BlogHeroCover src={coverSrc} alt={blog.title} />
            </div>
          ) : null}

          <div
            className="prose prose-slate mt-10 max-w-none break-words prose-headings:font-bold prose-headings:text-primary prose-h2:mt-10 prose-h2:text-2xl prose-h3:text-lg prose-p:leading-relaxed prose-a:font-medium prose-a:text-primary hover:prose-a:underline prose-strong:text-slate-900 prose-li:marker:text-secondary prose-img:rounded-xl prose-pre:overflow-x-auto"
            dangerouslySetInnerHTML={{ __html: articleHtml }}
          />

          {faqs.length > 0 ? (
            <div className="mt-2">
              <BlogFaqs faqs={faqs} />
              {trailingHtml ? (
                <div
                  className="prose prose-slate mt-8 max-w-none break-words prose-a:font-medium prose-a:text-primary hover:prose-a:underline prose-strong:text-slate-900"
                  dangerouslySetInnerHTML={{ __html: trailingHtml }}
                />
              ) : null}
            </div>
          ) : null}

          {blog.tags && blog.tags.length > 0 ? (
            <div className="mt-10 flex flex-wrap items-center gap-2">
              {blog.tags.map((tag) => (
                <span
                  key={tag}
                  className="rounded-full bg-slate-100 px-3 py-1 text-xs font-medium text-slate-600"
                >
                  #{tag}
                </span>
              ))}
            </div>
          ) : null}
        </div>
      </article>

      {/* Products showcase — help readers discover what Nizamify actually sells. */}
      {products.length > 0 ? (
        <section className="border-t border-slate-100 bg-white">
          <div className="container py-14">
            <div className="flex flex-col gap-3">
              <span className="inline-flex w-fit items-center gap-1.5 rounded-full bg-secondary/10 px-3 py-1 text-xs font-bold uppercase tracking-wider text-secondary">
                <Sparkles className="size-3.5" aria-hidden />
                Smart Products
              </span>
              <h2 className="text-2xl font-bold text-primary sm:text-3xl">
                Explore Nizamify Smart Products
              </h2>
              <p className="max-w-2xl text-sm text-slate-600 sm:text-base">
                Bring the automation you just read about into your home or business. Explore a few of
                our best-selling smart devices—shipped across Pakistan.
              </p>
            </div>

            <ul className="mt-10 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
              {products.map((p) => {
                const img = resolveProductMediaUrl(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-2xl border border-slate-100 bg-white shadow-sm transition hover:-translate-y-0.5 hover:shadow-md"
                  >
                    <Link href={`/products/${p.slug}`} className="block">
                      <div className="relative aspect-[4/3] bg-slate-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-slate-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">Rs {price.toFixed(2)}</span>
                          {showStrike ? (
                            <span className="ml-2 text-sm text-slate-400 line-through">
                              Rs {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 className="mt-8">
              <Link
                href="/products"
                className="inline-flex items-center gap-2 rounded-full bg-secondary px-6 py-2.5 text-sm font-semibold text-white shadow-sm transition-colors hover:bg-secondary/90"
              >
                Browse all products
                <ArrowRight className="size-4" aria-hidden />
              </Link>
            </div>
          </div>
        </section>
      ) : null}

      {/* Related articles — keep readers exploring more topics. */}
      {related.length > 0 ? (
        <section className="border-t border-slate-100">
          <div className="container py-14">
            <div className="mb-8 flex flex-wrap items-end justify-between gap-3">
              <div>
                <h2 className="text-2xl font-bold text-primary sm:text-3xl">Continue reading</h2>
                <p className="mt-1 text-sm text-slate-600">
                  More guides on smart home &amp; business automation in Pakistan.
                </p>
              </div>
              <Link
                href="/blogs"
                className="hidden items-center gap-1.5 text-sm font-semibold text-primary hover:text-secondary sm:inline-flex"
              >
                View all articles
                <ArrowRight className="size-4" aria-hidden />
              </Link>
            </div>

            <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
              {related.map((b) => {
                const relCover = resolvePublicMediaUrl(b.coverImage);
                return (
                  <article
                    key={b._id}
                    className="group flex flex-col overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm transition-shadow hover:shadow-md"
                  >
                    <Link
                      href={`/blogs/${b.slug}`}
                      className="relative block aspect-[1200/630] shrink-0 overflow-hidden bg-slate-100"
                    >
                      {relCover ? (
                        <Image
                          src={relCover}
                          alt={b.title}
                          fill
                          className="object-cover transition-transform duration-300 group-hover:scale-105"
                          sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                        />
                      ) : (
                        <div className="flex size-full items-center justify-center bg-gradient-to-br from-slate-100 to-slate-200 px-4 text-center text-xs font-medium text-slate-400">
                          No cover image
                        </div>
                      )}
                    </Link>
                    <div className="flex flex-1 flex-col p-5">
                      <p className="mb-2 text-xs font-semibold uppercase tracking-wide text-secondary">
                        {b.category?.name || "General"}
                      </p>
                      <h3 className="mb-2 line-clamp-2 text-lg font-semibold text-slate-900">
                        {b.title}
                      </h3>
                      <p className="line-clamp-3 flex-1 text-sm text-slate-600">
                        {b.excerpt || stripHtml(b.content).slice(0, 140)}
                      </p>
                      <Link
                        href={`/blogs/${b.slug}`}
                        className="mt-4 inline-flex items-center gap-1.5 text-sm font-semibold text-primary hover:underline"
                      >
                        Read article
                        <ArrowRight className="size-4" aria-hidden />
                      </Link>
                    </div>
                  </article>
                );
              })}
            </div>
          </div>
        </section>
      ) : null}

      {/* Closing CTA */}
      <section className="border-t border-slate-100 bg-primary">
        <div className="container py-14">
          <div className="max-w-2xl">
            <h2 className="text-2xl font-bold text-white sm:text-3xl">
              Ready to automate your home or business?
            </h2>
            <p className="mt-3 text-sm text-white/85 sm:text-base">
              Talk to the Nizamify team about smart automation tailored for Pakistan. We&apos;ll help
              you pick the right devices and set everything up.
            </p>
            <div className="mt-7 flex flex-wrap items-center gap-3">
              <SectionWhatsAppCta
                topic="smart home & business automation"
                className="rounded-full bg-secondary px-6 py-2.5 text-sm font-semibold text-white no-underline shadow-sm hover:bg-secondary/90 hover:no-underline"
              >
                Chat on WhatsApp
                <ArrowRight className="size-4" aria-hidden />
              </SectionWhatsAppCta>
              <Link
                href="/blogs"
                className="inline-flex items-center gap-2 rounded-full border-2 border-white/40 px-6 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-white/10"
              >
                <ArrowLeft className="size-4" aria-hidden />
                More articles
              </Link>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}
