import React from "react";
import { getBlog } from "@/services/cms/cms.service";
import { notFound } from "next/navigation";
import { ShareButton } from "@/components/ui/share-button";
import { Button } from "@/components/ui/button";
import { ArrowLeft, Calendar, FileX } from "lucide-react";
import Link from "next/link";
import Image from "next/image";
import dayjs from "dayjs";
import Navbar from "@/components/shared/Navbar";
import Footer from "@/components/shared/Footer";

import type { Metadata } from "next";
import { fetchSiteConfig } from "@/services/site-config.service";

export const revalidate = 60;

interface BlogDetailsPageProps {
  params: Promise<{ slug: string }>;
}

function decodeEntities(str: string): string {
  if (!str) return "";
  return str
    .replace(/&nbsp;/g, " ")
    .replace(/&#39;/g, "'")
    .replace(/&ldquo;/g, "“")
    .replace(/&rdquo;/g, "”")
    .replace(/&quot;/g, '"')
    .replace(/&amp;/g, "&")
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">");
}

export async function generateMetadata({ params }: BlogDetailsPageProps): Promise<Metadata> {
  const { slug } = await params;
  let blog = null;
  try {
    blog = await getBlog(slug);
  } catch (error) {
    console.error("SEO Metadata: Failed to fetch blog post:", error);
  }

  let brand = "Electronics Store";
  try {
    const siteConfig = await fetchSiteConfig();
    if (siteConfig.company_name) brand = siteConfig.company_name;
  } catch {}

  if (!blog) {
    return {
      title: "Blog Post Not Found",
      description: "The requested cooking story or recipe tip could not be found.",
    };
  }

  const seo = (blog as any).seo_meta || {};
  const title = seo.meta_title || decodeEntities(blog.title);

  // Strip html from content to get description snippet
  const cleanContent = blog.content ? blog.content.replace(/<[^>]*>/g, "") : "";
  const plainDescription = cleanContent
    .replace(/&nbsp;/g, " ")
    .replace(/&#39;/g, "'")
    .replace(/&ldquo;/g, "“")
    .replace(/&rdquo;/g, "”")
    .replace(/&quot;/g, '"')
    .replace(/&amp;/g, "&")
    .replace(/\s+/g, " ")
    .trim();
  
  const excerpt = plainDescription.slice(0, 155) + (plainDescription.length > 155 ? "..." : "");
  const description = seo.meta_description || excerpt || "Read the latest tech news, buying guides and product updates from our store.";
  const imageUrl = seo.og_image_url || blog.featured_image_url || "/images/og-image.webp";

  const absoluteImageUrl = imageUrl.startsWith("http")
    ? imageUrl
    : `${process.env.NEXT_PUBLIC_SITE_URL || "http://localhost:3000"}${imageUrl}`;

  const keywordsString = seo.keywords || `${blog.title}, electronics blog`;
  const keywords = keywordsString.split(",").map((k: string) => k.trim());

  return {
    title,
    description,
    keywords,
    metadataBase: new URL(process.env.NEXT_PUBLIC_SITE_URL || "http://localhost:3000"),
    alternates: {
      canonical: `/blogs/${blog.slug}`,
    },
    robots: seo.indexable === false ? "noindex, nofollow" : "index, follow",
    openGraph: {
      title,
      description,
      type: "article",
      url: `/blogs/${blog.slug}`,
      siteName: brand,
      locale: "en_US",
      images: [
        {
          url: absoluteImageUrl,
          alt: blog.title,
        },
      ],
    },
    twitter: {
      card: "summary_large_image",
      title,
      description,
      images: [absoluteImageUrl],
    },
  };
}

export default async function BlogDetailsPage({ params }: BlogDetailsPageProps) {
  const { slug } = await params;

  const blog = await getBlog(slug);

  if (!blog) {
    return (
      <>
        <Navbar />
        <div className="min-h-screen pt-20 flex flex-col items-center justify-center p-4 bg-slate-50/50">
          <div className="w-20 h-20 bg-white rounded-3xl border shadow-sm flex items-center justify-center mb-6">
            <FileX className="w-10 h-10 text-slate-300" />
          </div>
          <h1 className="text-2xl font-bold text-slate-900 uppercase tracking-tight">No Blog Data Found</h1>
          <p className="text-slate-500 text-sm mt-2 mb-8 text-center max-w-md">
            The blog post you are looking for does not exist or has been removed from the database.
          </p>
          <Button variant="outline" asChild className="rounded-xl font-bold uppercase text-xs tracking-widest px-8 h-11">
            <Link href="/">
              <ArrowLeft size={16} className="mr-2" />
              Back to Home
            </Link>
          </Button>
        </div>
        <Footer />
      </>
    );
  }

  return (
    <>
      <Navbar />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{
          __html: JSON.stringify({
            "@context": "https://schema.org",
            "@type": "BlogPosting",
            "headline": blog.title,
            "description": blog.content ? blog.content.replace(/<[^>]*>/g, "").trim().slice(0, 155) : "",
            "image": blog.featured_image_url || "",
            "datePublished": blog.created_at || new Date().toISOString(),
            "dateModified": blog.updated_at || new Date().toISOString(),
            "author": {
              "@type": "Organization",
              "name": "Electronics Store"
            },
            "publisher": {
              "@type": "Organization",
              "name": "Electronics Store",
              "logo": {
                "@type": "ImageObject",
                "url": `${process.env.NEXT_PUBLIC_SITE_URL || "http://localhost:3000"}/favicon.ico`
              }
            }
          })
        }}
      />
      <div className="w-full bg-white min-h-screen pb-20 pt-20 md:pt-28 overflow-x-hidden">
        <div className="container mx-auto px-4 md:px-6">
          {/* 1. Header Bar */}
          <div className="py-4 border-b flex items-center justify-between">
            <Button variant="outline" asChild className="rounded-lg h-9 text-xs">
              <Link href="/">
                <ArrowLeft size={14} className="mr-1.5" /> Back to Home
              </Link>
            </Button>
          </div>

          <div className="py-6 md:py-10 space-y-6">
            {/* 2. Top Featured Image */}
            {blog.featured_image_url ? (
              <div className="relative aspect-[2/1] md:aspect-[30/9] w-full rounded-2xl overflow-hidden border bg-slate-100">
                <Image
                  src={blog.featured_image_url}
                  alt={blog.title}
                  fill
                  priority
                  className="object-cover"
                />
              </div>
            ) : (
              <div className="relative aspect-[2/1] md:aspect-[30/9] w-full rounded-2xl bg-slate-100 border flex items-center justify-center text-muted-foreground text-sm">
                No featured image
              </div>
            )}

            {/* 3. Info Row & Giant Title */}
            <div className="space-y-4">
              <div className="flex items-center justify-between gap-4">
                <div className="flex items-center gap-3 text-xs text-muted-foreground">
                  {/* Date */}
                  <div className="flex items-center gap-1.5">
                    <Calendar size={14} className="text-slate-400" />
                    <span>{dayjs(blog.published_at || blog.created_at).format("MMMM DD, YYYY")}</span>
                  </div>
                  {/* Separator Dot */}
                  <div className="w-1 h-1 bg-slate-300 rounded-full" />
                  {/* Status pill */}
                  <span className="inline-flex items-center rounded-full bg-green-50 px-2 py-0.5 text-xs font-medium text-green-700 ring-1 ring-inset ring-green-600/20 capitalize">
                    {blog.status}
                  </span>
                </div>
                
                <ShareButton 
                  url={`${process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000'}/blogs/${blog.slug}`}
                  title={blog.title}
                  variant="button"
                  className="bg-slate-100 text-slate-700 hover:bg-slate-200 shadow-none border border-slate-200"
                />
              </div>

              {/* Giant Title */}
              <h1 className="text-3xl md:text-4xl font-extrabold text-slate-900 tracking-tight leading-tight">
                {decodeEntities(blog.title)}
              </h1>
            </div>

            {/* 4. Content Area - Strictly Boundary Constrained */}
            <div className="pt-6 md:pt-8 border-t border-slate-100 w-full min-w-0 max-w-full overflow-hidden">
              <div className="blog-details-content ql-snow w-full min-w-0 max-w-full">
                <div
                  className="ql-editor !w-full !max-w-full min-w-0 px-4 md:px-8 !py-0 !h-auto block
                [&_img]:w-full [&_img]:aspect-[2/1] md:[&_img]:aspect-[3/1] [&_img]:max-h-[400px] [&_img]:object-cover [&_img]:rounded-xl [&_img]:shadow-lg [&_img]:my-4
                [&_p]:text-slate-600 [&_p]:leading-relaxed [&_p]:m-0 [&_p]:min-h-[1.5em] [&_p]:w-full [&_p]:max-w-full
                [&_h1]:text-3xl md:[&_h1]:text-4xl [&_h1]:m-0 [&_h1]:font-black [&_h1]:text-slate-900 [&_h1]:tracking-tight [&_h1]:max-w-full
                [&_h2]:text-2xl md:[&_h2]:text-3xl [&_h2]:m-0 [&_h2]:font-black [&_h2]:text-slate-900 [&_h2]:tracking-tight [&_h2]:max-w-full
                [&_h3]:text-xl md:[&_h3]:text-2xl [&_h3]:m-0 [&_h3]:font-black [&_h3]:text-slate-900 [&_h3]:tracking-tight [&_h3]:max-w-full
                [&_a]:text-blue-600 [&_a]:underline [&_a]:break-all
                [&_strong]:text-slate-900 [&_strong]:font-bold
                [&_.ql-align-center]:text-center
                [&_.ql-align-right]:text-right
                [&_.ql-align-justify]:text-justify
                [&_.ql-size-small]:text-xs
                [&_.ql-size-large]:text-2xl
                [&_.ql-size-huge]:text-4xl"
                  dangerouslySetInnerHTML={{ __html: blog.content }}
                />
              </div>
              <style dangerouslySetInnerHTML={{
                __html: `
              /* SCOPED FIX FOR BLOG DETAILS ONLY */
              .blog-details-content .ql-editor ul {
                list-style-type: disc !important;
                padding-left: 1.5rem !important;
                margin-top: 0 !important;
                margin-bottom: 0 !important;
                display: block !important;
              }
              .blog-details-content .ql-editor ol {
                list-style-type: decimal !important;
                padding-left: 1.5rem !important;
                margin-top: 0 !important;
                margin-bottom: 0 !important;
                display: block !important;
              }
              .blog-details-content .ql-editor li {
                display: list-item !important;
                list-style: inherit !important;
                margin-top: 0 !important;
                margin-bottom: 0 !important;
                padding-left: 0.25em !important;
              }
              .blog-details-content .ql-editor li::before {
                content: none !important;
              }
              .blog-details-content .ql-editor p,
              .blog-details-content .ql-editor h1,
              .blog-details-content .ql-editor h2,
              .blog-details-content .ql-editor h3,
              .blog-details-content .ql-editor li {
                white-space: pre-wrap !important;
                word-wrap: break-word !important;
                overflow-wrap: break-word !important;
                word-break: break-word !important;
                max-width: 100% !important;
              }
              .blog-details-content .ql-editor p {
                min-height: 1.2em;
                width: 100% !important;
                display: block !important;
              }
              .blog-details-content .ql-editor * {
                max-width: 100% !important;
                margin-left: 0 !important;
                margin-right: 0 !important;
              }
              .blog-details-content .ql-editor a {
                word-break: break-all !important;
              }
            `}} />
            </div>
          </div>
        </div>
      </div>
      <Footer />
    </>
  );
}
