"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import { clsx } from "clsx";
import { TOPICS, type Topic } from "@/lib/blog/topics";
import { formatLegacyDate } from "@/lib/legacy/content";

type Card = {
  id: number;
  slug: string;
  title: string;
  excerpt: string;
  date: string;
  featuredImage: string;
  topic: Topic;
};

export function BlogGrid({ posts }: { posts: Card[] }) {
  const [active, setActive] = useState<Topic | "All">("All");
  const [query, setQuery] = useState("");

  const counts = useMemo(() => {
    const out: Record<string, number> = { All: posts.length };
    for (const t of TOPICS) out[t] = 0;
    for (const p of posts) out[p.topic] += 1;
    return out;
  }, [posts]);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return posts.filter((p) => {
      if (active !== "All" && p.topic !== active) return false;
      if (!q) return true;
      return (
        p.title.toLowerCase().includes(q) ||
        p.excerpt.toLowerCase().includes(q)
      );
    });
  }, [posts, active, query]);

  const filters: Array<Topic | "All"> = ["All", ...TOPICS];

  return (
    <div>
      <div className="mb-6">
        <input
          type="search"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="Search posts…"
          className="w-full rounded-lg border border-[var(--color-line)] bg-white px-4 py-3 text-[15px] text-[var(--color-ink)] placeholder:text-[var(--color-slate)] focus:border-[var(--color-blue)] focus:outline-none focus:ring-2 focus:ring-[var(--color-blue)]/20"
          aria-label="Search posts"
        />
      </div>

      <div className="mb-10 flex flex-wrap gap-2">
        {filters.map((t) => {
          const isActive = active === t;
          const count = counts[t] ?? 0;
          if (t !== "All" && count === 0) return null;
          return (
            <button
              key={t}
              type="button"
              onClick={() => setActive(t)}
              className={clsx(
                "inline-flex items-center gap-2 rounded-full border px-4 py-1.5 text-[13px] font-semibold transition-all",
                isActive
                  ? "border-[var(--color-blue)] bg-[var(--color-blue)] text-white shadow-sm"
                  : "border-[var(--color-line)] bg-white text-[var(--color-slate)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]",
              )}
            >
              {t}
              <span
                className={clsx(
                  "rounded-full px-1.5 py-0.5 text-[11px] font-bold",
                  isActive
                    ? "bg-white/20 text-white"
                    : "bg-[var(--color-mist)] text-[var(--color-blue)]",
                )}
              >
                {count}
              </span>
            </button>
          );
        })}
      </div>

      {filtered.length === 0 ? (
        <div className="rounded-lg border border-dashed border-[var(--color-line)] bg-[var(--color-mist)]/40 py-16 text-center text-[15px] text-[var(--color-slate)]">
          No posts match your filters.
        </div>
      ) : (
        <div className="grid grid-cols-1 gap-8 md:grid-cols-2 lg:grid-cols-3">
          {filtered.map((p) => (
            <Link
              key={p.id}
              href={`/blog/${p.slug}`}
              className="group flex flex-col overflow-hidden rounded-lg border border-[var(--color-line)] bg-white transition-all duration-200 hover:-translate-y-1 hover:border-[var(--color-blue)] hover:shadow-lg motion-reduce:transform-none motion-reduce:transition-none"
            >
              <div className="relative aspect-[16/10] w-full overflow-hidden bg-[var(--color-mist)]">
                {p.featuredImage ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={p.featuredImage}
                    alt=""
                    className="h-full w-full object-cover transition-transform duration-500 ease-out group-hover:scale-[1.04] motion-reduce:transform-none motion-reduce:transition-none"
                    loading="lazy"
                  />
                ) : (
                  <div
                    aria-hidden
                    className="flex h-full w-full flex-col items-center justify-center"
                    style={{
                      background:
                        "linear-gradient(135deg, rgba(30,64,255,0.08), rgba(30,64,255,0.18))",
                    }}
                  >
                    <div className="flex h-14 w-14 items-center justify-center rounded-full bg-white/80 font-display text-[22px] font-extrabold text-[var(--color-blue)] shadow-sm">
                      {p.topic.slice(0, 1)}
                    </div>
                    <div className="mt-3 text-[10px] font-bold uppercase tracking-[0.18em] text-[var(--color-blue-deep)]">
                      {p.topic}
                    </div>
                  </div>
                )}
                <span className="absolute left-3 top-3 inline-flex items-center rounded-full bg-white/95 px-3 py-1 text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)] shadow-sm">
                  {p.topic}
                </span>
              </div>
              <div className="flex flex-1 flex-col p-5">
                {p.date && (
                  <span className="text-[11px] font-semibold uppercase tracking-wider text-[var(--color-slate)]">
                    {formatLegacyDate(p.date)}
                  </span>
                )}
                <h3 className="mt-2 font-display text-[19px] font-bold leading-tight text-[var(--color-ink)] group-hover:text-[var(--color-blue)]">
                  {p.title}
                </h3>
                {p.excerpt && (
                  <p className="mt-2 line-clamp-3 text-[14px] leading-relaxed text-[var(--color-slate)]">
                    {p.excerpt}
                  </p>
                )}
                <span className="mt-4 inline-flex items-center gap-1 text-[13px] font-semibold text-[var(--color-blue)]">
                  Read article
                  <span className="transition-transform duration-200 group-hover:translate-x-1 motion-reduce:transform-none">
                    →
                  </span>
                </span>
              </div>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}
