"use client";

import { useState, useEffect, useCallback } from "react";
import { useParams } from "next/navigation";
import Link from "next/link";
import { motion, AnimatePresence } from "framer-motion";
import {
  ArrowLeft,
  Clock,
  Eye,
  Calendar,
  User,
  Tag,
  ChevronDown,
  Sparkles,
  BookOpen,
} from "lucide-react";
import { fetchBlog, fetchBlogs } from "@/lib/api";
import type { Blog, BlogFAQ } from "@/lib/types";
import { cn } from "@/lib/utils";

// ── Helpers ───────────────────────────────────────────────────────────────────

function formatDate(iso: string) {
  try {
    return new Date(iso).toLocaleDateString("en-IN", {
      day: "numeric",
      month: "short",
      year: "numeric",
    });
  } catch {
    return iso;
  }
}

// ── FAQ Accordion ─────────────────────────────────────────────────────────────

function FAQItem({ faq, index }: { faq: BlogFAQ; index: number }) {
  const [open, setOpen] = useState(false);
  return (
    <div className="border-b border-gray-100 last:border-0">
      <button
        onClick={() => setOpen(!open)}
        className="w-full text-left py-4 flex justify-between items-start gap-3"
      >
        <span className="font-bold text-gray-900 text-sm leading-relaxed">
          {index + 1}. {faq.question}
        </span>
        <ChevronDown
          className={cn(
            "w-4 h-4 text-gray-400 shrink-0 transition-transform duration-200 mt-0.5",
            open && "rotate-180"
          )}
        />
      </button>
      <AnimatePresence>
        {open && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: "auto", opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.2 }}
            className="overflow-hidden"
          >
            <p className="pb-4 text-gray-600 text-sm leading-relaxed">{faq.answer}</p>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

// ── Related article card ──────────────────────────────────────────────────────

function RelatedCard({ blog }: { blog: Blog }) {
  return (
    <Link href={`/blogs/${blog.slug}`}>
      <div className="bg-white rounded-2xl border border-gray-100 p-4 hover:shadow-md transition-all duration-200 group h-full flex flex-col">
        <span className="text-xs font-bold text-blue-600 bg-blue-50 px-2 py-1 rounded-full w-fit mb-3">
          {blog.category}
        </span>
        <h4 className="text-sm font-black text-gray-900 line-clamp-2 group-hover:text-blue-600 transition-colors flex-1">
          {blog.title}
        </h4>
        <div className="flex items-center gap-3 mt-3">
          <span className="text-xs text-gray-400 flex items-center gap-1">
            <Clock className="w-3 h-3" />
            {blog.readTime} min
          </span>
          <span className="text-xs text-gray-400">{formatDate(blog.publishedAt)}</span>
        </div>
      </div>
    </Link>
  );
}

// ── Skeleton ──────────────────────────────────────────────────────────────────

function BlogSkeleton() {
  return (
    <div className="animate-pulse space-y-6">
      <div className="h-12 bg-gray-200 rounded-2xl w-3/4" />
      <div className="h-6 bg-gray-100 rounded-xl w-1/2" />
      <div className="space-y-3">
        {Array.from({ length: 8 }).map((_, i) => (
          <div key={i} className={cn("h-4 bg-gray-100 rounded-lg", i % 3 === 2 ? "w-2/3" : "w-full")} />
        ))}
      </div>
    </div>
  );
}

// ── Main Page ─────────────────────────────────────────────────────────────────

export default function BlogDetailPage() {
  const params = useParams();
  const slug = params?.slug as string;

  const [blog, setBlog] = useState<Blog | null>(null);
  const [related, setRelated] = useState<Blog[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    if (!slug) return;
    setLoading(true);
    setError(null);
    try {
      const b = await fetchBlog(slug);
      setBlog(b);
      // Fetch related blogs (same category)
      try {
        const rel = await fetchBlogs({ category: b.category, limit: 3, status: "published" });
        setRelated((rel.blogs ?? []).filter((r) => r.id !== b.id).slice(0, 3));
      } catch {
        // Related articles are optional
      }
    } catch {
      setError("Blog post not found or failed to load.");
    } finally {
      setLoading(false);
    }
  }, [slug]);

  useEffect(() => {
    load();
  }, [load]);

  if (error) {
    return (
      <div className="min-h-screen bg-gray-50 flex flex-col items-center justify-center gap-4 p-4">
        <div className="w-14 h-14 rounded-2xl bg-red-50 flex items-center justify-center">
          <BookOpen className="w-7 h-7 text-red-400" />
        </div>
        <p className="text-gray-700 font-bold text-lg">{error}</p>
        <Link
          href="/blogs"
          className="flex items-center gap-2 text-sm font-bold text-blue-600 hover:underline"
        >
          <ArrowLeft className="w-4 h-4" />
          Back to Blog
        </Link>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Hero */}
      <div className="bg-gradient-to-br from-gray-900 via-blue-950 to-gray-900 text-white pt-10 pb-16 px-4">
        <div className="max-w-4xl mx-auto">
          <Link
            href="/blogs"
            className="inline-flex items-center gap-2 text-sm font-bold text-blue-300 hover:text-white transition-colors mb-6"
          >
            <ArrowLeft className="w-4 h-4" />
            Back to Blog
          </Link>

          {loading ? (
            <div className="space-y-4 animate-pulse">
              <div className="h-8 bg-white/10 rounded-2xl w-24" />
              <div className="h-12 bg-white/20 rounded-2xl w-full" />
              <div className="h-12 bg-white/10 rounded-2xl w-2/3" />
            </div>
          ) : blog ? (
            <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }}>
              <div className="flex items-center gap-2 mb-4 flex-wrap">
                <span className="text-xs font-bold uppercase tracking-widest text-blue-300 bg-blue-950/60 border border-blue-800 px-3 py-1.5 rounded-full">
                  {blog.category}
                </span>
                {blog.aiGenerated && (
                  <span className="text-xs font-bold text-purple-300 bg-purple-950/60 border border-purple-800 px-3 py-1.5 rounded-full flex items-center gap-1">
                    <Sparkles className="w-3 h-3" />
                    DriveHub Editorial
                  </span>
                )}
              </div>
              <h1 className="text-3xl sm:text-4xl font-black leading-tight mb-6">{blog.title}</h1>
              <div className="flex flex-wrap items-center gap-4 text-sm text-gray-300">
                <span className="flex items-center gap-2">
                  <User className="w-4 h-4 text-blue-300" />
                  {blog.author}
                </span>
                <span className="flex items-center gap-2">
                  <Calendar className="w-4 h-4 text-blue-300" />
                  {formatDate(blog.publishedAt)}
                </span>
                <span className="flex items-center gap-2">
                  <Clock className="w-4 h-4 text-blue-300" />
                  {blog.readTime} min read
                </span>
                {blog.views > 0 && (
                  <span className="flex items-center gap-2">
                    <Eye className="w-4 h-4 text-blue-300" />
                    {blog.views.toLocaleString()} views
                  </span>
                )}
              </div>
            </motion.div>
          ) : null}
        </div>
      </div>

      {/* Main content */}
      <div className="max-w-4xl mx-auto px-4 py-10">
        {loading ? (
          <BlogSkeleton />
        ) : blog ? (
          <div className="lg:grid lg:grid-cols-[1fr,260px] lg:gap-10 items-start">
            {/* Article body */}
            <article>
              {/* Tags */}
              {blog.tags?.length > 0 && (
                <div className="flex items-center gap-2 flex-wrap mb-6">
                  <Tag className="w-4 h-4 text-gray-400" />
                  {blog.tags.map((tag) => (
                    <span key={tag} className="text-xs bg-gray-100 text-gray-600 px-2.5 py-1 rounded-full font-medium">
                      {tag}
                    </span>
                  ))}
                </div>
              )}

              {/* Excerpt */}
              {blog.excerpt && (
                <div className="bg-blue-50 border-l-4 border-blue-500 rounded-r-2xl p-4 mb-8">
                  <p className="text-sm text-blue-800 font-medium leading-relaxed">{blog.excerpt}</p>
                </div>
              )}

              {/* Main HTML content */}
              <div
                className="blog-content text-gray-700"
                dangerouslySetInnerHTML={{ __html: blog.content }}
              />

              {/* FAQ Section */}
              {blog.faqSchema?.length > 0 && (
                <div className="mt-12">
                  <h2 className="text-xl font-black text-gray-900 mb-6 flex items-center gap-2">
                    <span className="w-8 h-8 rounded-xl bg-blue-100 flex items-center justify-center text-blue-600 text-sm font-black">?</span>
                    Frequently Asked Questions
                  </h2>
                  <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
                    {blog.faqSchema.map((faq, i) => (
                      <FAQItem key={i} faq={faq} index={i} />
                    ))}
                  </div>
                </div>
              )}

              {/* Related Articles */}
              {related.length > 0 && (
                <div className="mt-12">
                  <h2 className="text-xl font-black text-gray-900 mb-6">Related Articles</h2>
                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                    {related.map((r) => (
                      <RelatedCard key={r.id} blog={r} />
                    ))}
                  </div>
                </div>
              )}
            </article>

            {/* Sidebar */}
            <aside className="hidden lg:block sticky top-8 space-y-6">
              {/* Article info */}
              <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 space-y-3">
                <h3 className="text-sm font-black text-gray-900 uppercase tracking-wider">About this article</h3>
                <div className="space-y-2 text-sm text-gray-600">
                  <div className="flex items-center justify-between">
                    <span className="text-gray-400 font-medium">Author</span>
                    <span className="font-bold">{blog.author}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-gray-400 font-medium">Words</span>
                    <span className="font-bold">{blog.wordCount?.toLocaleString()}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-gray-400 font-medium">Read time</span>
                    <span className="font-bold">{blog.readTime} min</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-gray-400 font-medium">Views</span>
                    <span className="font-bold">{blog.views?.toLocaleString()}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-gray-400 font-medium">Updated</span>
                    <span className="font-bold text-xs">{formatDate(blog.updatedAt)}</span>
                  </div>
                </div>
              </div>

              {/* Tags sidebar */}
              {blog.tags?.length > 0 && (
                <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5">
                  <h3 className="text-sm font-black text-gray-900 uppercase tracking-wider mb-3">Tags</h3>
                  <div className="flex flex-wrap gap-2">
                    {blog.tags.map((tag) => (
                      <span key={tag} className="text-xs bg-gray-100 text-gray-600 px-2.5 py-1.5 rounded-xl font-medium hover:bg-blue-50 hover:text-blue-600 transition-colors cursor-pointer">
                        {tag}
                      </span>
                    ))}
                  </div>
                </div>
              )}

              {/* CTA */}
              <div className="bg-gradient-to-br from-blue-600 to-cyan-500 rounded-2xl p-5 text-white">
                <h3 className="font-black text-lg mb-2">Find Your Perfect Car</h3>
                <p className="text-sm text-blue-100 mb-4">Use our smart search to find the best car for you</p>
                <Link
                  href="/cars"
                  className="block text-center bg-white text-blue-600 font-bold text-sm px-4 py-3 rounded-xl hover:bg-blue-50 transition-colors"
                >
                  Explore Cars
                </Link>
              </div>
            </aside>
          </div>
        ) : null}
      </div>

      <style>{`
        .blog-content h1 { font-size: 2rem; font-weight: 900; color: #111827; margin: 2rem 0 1rem; line-height: 1.2; }
        .blog-content h2 { font-size: 1.5rem; font-weight: 900; color: #111827; margin: 2rem 0 0.75rem; line-height: 1.3; }
        .blog-content h3 { font-size: 1.25rem; font-weight: 800; color: #1f2937; margin: 1.5rem 0 0.5rem; line-height: 1.4; }
        .blog-content h4 { font-size: 1.1rem; font-weight: 700; color: #374151; margin: 1.25rem 0 0.5rem; }
        .blog-content p  { margin: 0 0 1.25rem; line-height: 1.75; color: #374151; }
        .blog-content ul { list-style: disc; padding-left: 1.5rem; margin: 0 0 1.25rem; }
        .blog-content ol { list-style: decimal; padding-left: 1.5rem; margin: 0 0 1.25rem; }
        .blog-content li { margin-bottom: 0.4rem; line-height: 1.7; color: #374151; }
        .blog-content a  { color: #2563eb; text-decoration: underline; }
        .blog-content a:hover { color: #1d4ed8; }
        .blog-content strong { font-weight: 700; color: #111827; }
        .blog-content em { font-style: italic; }
        .blog-content blockquote { border-left: 4px solid #3b82f6; padding: 0.75rem 1rem; margin: 1.5rem 0; background: #eff6ff; border-radius: 0 0.75rem 0.75rem 0; color: #1e40af; }
        .blog-content code { background: #f3f4f6; padding: 0.15rem 0.4rem; border-radius: 0.375rem; font-family: monospace; font-size: 0.875em; }
        .blog-content pre  { background: #1f2937; color: #f9fafb; padding: 1.25rem; border-radius: 0.75rem; overflow-x: auto; margin: 1.5rem 0; }
        .blog-content table { width: 100%; border-collapse: collapse; margin: 1.5rem 0; font-size: 0.9rem; }
        .blog-content th { background: #f3f4f6; font-weight: 700; padding: 0.75rem 1rem; text-align: left; border: 1px solid #e5e7eb; }
        .blog-content td { padding: 0.625rem 1rem; border: 1px solid #e5e7eb; }
        .blog-content tr:nth-child(even) td { background: #f9fafb; }
        .blog-content img { max-width: 100%; height: auto; border-radius: 0.75rem; margin: 1.5rem 0; }
        .blog-content hr { border: 0; border-top: 1px solid #e5e7eb; margin: 2rem 0; }
      `}</style>
    </div>
  );
}
