"use client";

import Image from "next/image";
import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { ArrowUpRight, CalendarDays } from "lucide-react";
import { apiBaseUrl, apiHeaders, apiPath } from "@/lib/api-url";
import { routePath } from "@/lib/route-url";
import type { BlogPost } from "@/lib/blogs";

const allCategory = "All";

type BlogListPageClientProps = {
  initialPosts: BlogPost[];
};

export function BlogListPageClient({ initialPosts }: BlogListPageClientProps) {
  const [posts, setPosts] = useState<BlogPost[]>(initialPosts);
  const [activeCategory, setActiveCategory] = useState(allCategory);

  useEffect(() => {
    async function loadBlogs() {
      try {
        const response = await fetch(`${apiBaseUrl}${apiPath("/api/blogs")}`, {
          cache: "no-store",
          headers: apiHeaders(),
        });

        if (!response.ok) {
          return;
        }

        const data = (await response.json()) as { blogs?: BlogPost[] };
        setPosts(data.blogs ?? []);
      } catch {
        setPosts(initialPosts);
      }
    }

    loadBlogs();
  }, [initialPosts]);

  const categories = useMemo(() => {
    return [allCategory, ...Array.from(new Set(posts.map((post) => post.category)))];
  }, [posts]);

  const filteredPosts = useMemo(() => {
    if (activeCategory === allCategory) {
      return posts;
    }

    return posts.filter((post) => post.category === activeCategory);
  }, [activeCategory, posts]);

  return (
    <main className="bg-white font-['Space_Grotesk']">
      <section className="border-b border-border bg-slate-50">
        <div className="mx-auto flex max-w-7xl flex-wrap justify-center gap-2 px-4 py-7">
          {categories.map((category) => {
            const active = activeCategory === category;

            return (
              <button
                key={category}
                type="button"
                onClick={() => setActiveCategory(category)}
                className={`rounded-full border px-4 py-2 text-sm font-bold transition-all ${
                  active
                    ? "border-primary bg-primary text-primary-foreground shadow-[0_10px_26px_rgba(211,47,47,0.18)]"
                    : "border-border bg-white text-muted-foreground hover:border-primary/40 hover:text-primary"
                }`}
              >
                {category}
              </button>
            );
          })}
        </div>
      </section>

      <section className="mx-auto max-w-7xl px-4 py-14 2xl:py-20">
        {filteredPosts.length === 0 ? (
          <div className="rounded-3xl border border-dashed border-border bg-slate-50 p-10 text-center">
            <p className="text-sm font-bold text-muted-foreground">No database blogs found.</p>
          </div>
        ) : (
          <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
            {filteredPosts.map((post) => (
              <div key={post.slug}>
                <Link
                  href={routePath(`/blog/${post.slug}`)}
                  className="group block h-full overflow-hidden rounded-3xl border border-border bg-card transition-all duration-300 hover:-translate-y-1 hover:border-primary/30"
                >
                  <div className="relative aspect-[3/2] overflow-hidden bg-slate-100">
                    <Image
                      src={post.image}
                      alt={post.imageAlt}
                      fill
                      sizes="(min-width: 1024px) 33vw, (min-width: 768px) 50vw, 100vw"
                      className="object-cover transition-transform duration-700 group-hover:scale-105"
                    />
                    <span className="absolute left-4 top-4 rounded-full bg-white/90 px-3 py-1 text-[10px] font-black uppercase tracking-[0.18em] text-primary backdrop-blur">
                      {post.category}
                    </span>
                  </div>

                  <div className="p-6">
                    <div className="flex items-center gap-2 text-xs font-semibold text-muted-foreground">
                      <CalendarDays className="h-4 w-4 text-primary" />
                      <span>{post.date}</span>
                      <span aria-hidden="true">&bull;</span>
                      <span>{post.readTime}</span>
                    </div>
                    <h3 className="mt-4 text-xl font-black leading-tight tracking-tight text-foreground group-hover:text-primary">
                      {post.title}
                    </h3>
                    <p className="mt-3 text-sm leading-relaxed text-muted-foreground">
                      {truncateText(post.excerpt)}
                    </p>
                    <span className="mt-5 inline-flex items-center gap-2 text-sm font-bold text-primary">
                      Read article
                      <ArrowUpRight className="h-4 w-4 transition-transform group-hover:translate-x-0.5 group-hover:-translate-y-0.5" />
                    </span>
                  </div>
                </Link>
              </div>
            ))}
          </div>
        )}
      </section>
    </main>
  );
}

function truncateText(value: string, maxLength = 150) {
  return value.length > maxLength ? `${value.slice(0, maxLength).trim()}...` : value;
}
