"use client";

import { motion, useInView } from "framer-motion";
import { useRef, useState, useEffect } from "react";
import { Navbar } from "@/components/home/Navbar";
import { Footer } from "@/components/home/Footer";
import { PageHeader } from "@/components/shared/PageHeader";
import { Clock, User, ArrowRight, Tag, Loader2 } from "lucide-react";
import Link from "next/link";
import api from "@/lib/api";
import type { Post, BlogCategory } from "@/lib/types";

export default function BlogPage() {
  const [posts, setPosts] = useState<Post[]>([]);
  const [categories, setCategories] = useState<BlogCategory[]>([]);
  const [activeCategory, setActiveCategory] = useState<string>("all");
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [loading, setLoading] = useState(true);

  const ref = useRef(null);
  const isInView = useInView(ref, { once: true, margin: "-50px" });

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

  useEffect(() => {
    fetchPosts();
  }, [activeCategory, currentPage]);

  async function fetchCategories() {
    try {
      const res = await api.get("/api/posts/categories");
      setCategories(res.data.data || res.data);
    } catch {
      // silently fail
    }
  }

  async function fetchPosts() {
    setLoading(true);
    try {
      const params: Record<string, string | number> = {
        page: currentPage,
        per_page: 9,
      };
      if (activeCategory !== "all") {
        params.category = activeCategory;
      }
      const res = await api.get("/api/posts", { params });
      const data = res.data;
      setPosts(data.data || []);
      setTotalPages(data.meta?.last_page || 1);
    } catch {
      setPosts([]);
    } finally {
      setLoading(false);
    }
  }

  const featured = posts.find((p) => p.is_featured);
  const rest = featured ? posts.filter((p) => p.id !== featured.id) : posts;

  function formatDate(dateStr: string | null) {
    if (!dateStr) return "";
    return new Date(dateStr).toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
      year: "numeric",
    });
  }

  return (
    <div className="flex flex-1 flex-col">
      <Navbar />

      <PageHeader
        title="Blog"
        breadcrumbs={[
          { label: "Home", href: "/" },
          { label: "Blog" },
        ]}
        backgroundImage="https://images.unsplash.com/photo-1560518883-ce09059eeffa?q=80&w=1973&auto=format&fit=crop"
      />

      {/* Featured Post */}
      {featured && (
        <section className="py-16 lg:py-20 bg-white">
          <div className="mx-auto max-w-7xl px-6 lg:px-8">
            <motion.div
              initial={{ opacity: 0, y: 30 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.7 }}
            >
              <Link
                href={`/blog/${featured.slug}`}
                className="grid lg:grid-cols-2 gap-8 group cursor-pointer"
              >
                <div className="relative aspect-[16/10] overflow-hidden">
                  {featured.featured_image ? (
                    <img
                      src={featured.featured_image}
                      alt={featured.featured_image_alt || featured.title}
                      className="h-full w-full object-cover transition-transform duration-700 group-hover:scale-105"
                    />
                  ) : (
                    <div className="h-full w-full bg-obsidian-100 flex items-center justify-center">
                      <span className="text-obsidian-300 text-sm">No image</span>
                    </div>
                  )}
                  <div className="absolute top-4 left-4 bg-primary text-white text-xs font-semibold px-3 py-1.5 uppercase tracking-wider">
                    Featured
                  </div>
                </div>
                <div className="flex flex-col justify-center">
                  <div className="flex items-center gap-4 text-xs text-obsidian-400 mb-4">
                    {featured.category && (
                      <span className="bg-obsidian-50 px-3 py-1 font-medium uppercase tracking-wider">
                        {featured.category.name}
                      </span>
                    )}
                    <div className="flex items-center gap-1.5">
                      <Clock size={12} />
                      <span>{featured.reading_time_minutes} min read</span>
                    </div>
                  </div>
                  <h2 className="font-display text-2xl sm:text-3xl font-bold text-obsidian-700 group-hover:text-primary transition-colors leading-tight">
                    {featured.title}
                  </h2>
                  {featured.excerpt && (
                    <p className="mt-4 text-base text-obsidian-400 leading-relaxed">
                      {featured.excerpt}
                    </p>
                  )}
                  <div className="flex items-center gap-3 mt-6">
                    {featured.author?.avatar ? (
                      <img
                        src={featured.author.avatar}
                        alt={featured.author.name}
                        className="w-8 h-8 rounded-full object-cover"
                      />
                    ) : (
                      <div className="w-8 h-8 bg-obsidian-200 rounded-full" />
                    )}
                    <div>
                      <p className="text-sm font-semibold text-obsidian-700">
                        {featured.author?.name}
                      </p>
                      <p className="text-xs text-obsidian-400">
                        {formatDate(featured.published_at)}
                      </p>
                    </div>
                  </div>
                  <span className="inline-flex items-center gap-2 mt-6 text-xs font-semibold text-primary uppercase tracking-wider">
                    Read Article <ArrowRight size={12} />
                  </span>
                </div>
              </Link>
            </motion.div>
          </div>
        </section>
      )}

      {/* Blog Grid */}
      <section className="py-16 lg:py-24 bg-obsidian-50" ref={ref}>
        <div className="mx-auto max-w-7xl px-6 lg:px-8">
          {/* Category Filters */}
          <div className="flex gap-2 mb-12 flex-wrap">
            <button
              onClick={() => {
                setActiveCategory("all");
                setCurrentPage(1);
              }}
              className={`px-4 py-2 text-xs font-semibold uppercase tracking-wider transition-all border ${
                activeCategory === "all"
                  ? "bg-primary text-white border-primary"
                  : "bg-white text-obsidian-500 hover:bg-primary hover:text-white border-obsidian-100"
              }`}
            >
              All
            </button>
            {categories.map((cat) => (
              <button
                key={cat.id}
                onClick={() => {
                  setActiveCategory(cat.slug);
                  setCurrentPage(1);
                }}
                className={`px-4 py-2 text-xs font-semibold uppercase tracking-wider transition-all border ${
                  activeCategory === cat.slug
                    ? "bg-primary text-white border-primary"
                    : "bg-white text-obsidian-500 hover:bg-primary hover:text-white border-obsidian-100"
                }`}
              >
                {cat.name}
              </button>
            ))}
          </div>

          {/* Loading State */}
          {loading ? (
            <div className="flex items-center justify-center py-20">
              <Loader2 className="animate-spin text-primary" size={32} />
            </div>
          ) : rest.length === 0 ? (
            <div className="text-center py-20">
              <p className="text-obsidian-400 text-lg">No blog posts found.</p>
            </div>
          ) : (
            <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-8">
              {rest.map((post, i) => (
                <motion.article
                  key={post.id}
                  initial={{ opacity: 0, y: 40 }}
                  animate={isInView ? { opacity: 1, y: 0 } : {}}
                  transition={{ duration: 0.5, delay: i * 0.08 }}
                  className="group bg-white border border-obsidian-100 hover:shadow-card transition-shadow"
                >
                  <Link href={`/blog/${post.slug}`} className="block">
                    <div className="relative aspect-[16/10] overflow-hidden">
                      {post.featured_image ? (
                        <img
                          src={post.featured_image}
                          alt={post.featured_image_alt || post.title}
                          className="h-full w-full object-cover transition-transform duration-700 group-hover:scale-110"
                        />
                      ) : (
                        <div className="h-full w-full bg-obsidian-100 flex items-center justify-center">
                          <span className="text-obsidian-300 text-sm">No image</span>
                        </div>
                      )}
                    </div>
                    <div className="p-6">
                      <div className="flex items-center gap-3 text-xs text-obsidian-400 mb-3">
                        {post.category && (
                          <div className="flex items-center gap-1.5">
                            <Tag size={12} />
                            <span>{post.category.name}</span>
                          </div>
                        )}
                        <div className="flex items-center gap-1.5">
                          <Clock size={12} />
                          <span>{post.reading_time_minutes} min read</span>
                        </div>
                      </div>
                      <h3 className="font-display text-base font-bold text-obsidian-700 group-hover:text-primary transition-colors leading-snug">
                        {post.title}
                      </h3>
                      {post.excerpt && (
                        <p className="mt-2 text-sm text-obsidian-400 leading-relaxed line-clamp-2">
                          {post.excerpt}
                        </p>
                      )}
                      <div className="flex items-center justify-between mt-5 pt-4 border-t border-obsidian-100">
                        <div className="flex items-center gap-2">
                          <User size={12} className="text-obsidian-400" />
                          <span className="text-xs text-obsidian-400">
                            {post.author?.name}
                          </span>
                        </div>
                        <span className="text-xs font-semibold text-primary uppercase tracking-wider inline-flex items-center gap-1">
                          Read More <ArrowRight size={10} />
                        </span>
                      </div>
                    </div>
                  </Link>
                </motion.article>
              ))}
            </div>
          )}

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="mt-12 flex items-center justify-center gap-2">
              {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
                <button
                  key={page}
                  onClick={() => setCurrentPage(page)}
                  className={`w-10 h-10 flex items-center justify-center text-sm font-semibold transition-colors ${
                    page === currentPage
                      ? "bg-primary text-white"
                      : "bg-white border border-obsidian-200 text-obsidian-500 hover:border-primary hover:text-primary"
                  }`}
                >
                  {page}
                </button>
              ))}
            </div>
          )}
        </div>
      </section>

      <Footer />
    </div>
  );
}
