"use client";

import { useMemo, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import ProductCard, { type ProductView } from "./ProductCard";
import { LayoutGrid, Search, X, SearchX } from "lucide-react";

interface CategoryView {
  _id: string;
  name: string;
  slug: string;
}

const TR_NORMALIZE: Record<string, string> = {
  ç: "c",
  ğ: "g",
  ı: "i",
  i̇: "i",
  ö: "o",
  ş: "s",
  ü: "u",
};

function normalize(value: string): string {
  return value
    .toLocaleLowerCase("tr-TR")
    .split("")
    .map((ch) => TR_NORMALIZE[ch] ?? ch)
    .join("")
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "");
}

export default function PortfolioBrowser({
  categories,
  products,
}: {
  categories: CategoryView[];
  products: ProductView[];
}) {
  const [activeId, setActiveId] = useState<string>("all");
  const [query, setQuery] = useState<string>("");

  const productsByCategory = useMemo(() => {
    const map: Record<string, ProductView[]> = { all: products };
    for (const c of categories) map[c._id] = [];
    for (const p of products) {
      const k = (p as ProductView & { categoryId?: string }).categoryId;
      if (k && map[k]) map[k].push(p);
    }
    return map;
  }, [categories, products]);

  const filtered = useMemo(() => {
    const base =
      activeId === "all" ? products : productsByCategory[activeId] ?? [];
    const q = normalize(query.trim());
    if (!q) return base;
    return base.filter((p) => {
      const title = normalize(p.title ?? "");
      const desc = normalize(p.description ?? "");
      return title.includes(q) || desc.includes(q);
    });
  }, [activeId, query, products, productsByCategory]);

  const trimmedQuery = query.trim();

  return (
    <div>
      {/* Search bar */}
      <div className="mb-5">
        <div className="relative max-w-2xl mx-auto">
          <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-brand-400 pointer-events-none" />
          <input
            type="text"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Tasarım adı veya açıklama ara..."
            className="w-full glass rounded-full pl-11 pr-11 py-3 text-sm text-white placeholder:text-brand-400 outline-none focus:border-brand-400 transition"
          />
          {query && (
            <button
              type="button"
              onClick={() => setQuery("")}
              aria-label="Aramayı temizle"
              className="absolute right-3 top-1/2 -translate-y-1/2 w-7 h-7 rounded-full bg-brand-700/50 hover:bg-brand-700 text-brand-100 flex items-center justify-center transition"
            >
              <X className="w-3.5 h-3.5" />
            </button>
          )}
        </div>
        {trimmedQuery && (
          <p className="mt-2 text-center text-xs text-brand-300">
            <span className="font-semibold text-white">{filtered.length}</span>{" "}
            sonuç bulundu
            {activeId !== "all" && " (seçili kategoride)"}
          </p>
        )}
      </div>

      {/* Tabs */}
      <div className="flex flex-wrap gap-2 mb-8 justify-center">
        <CategoryTab
          label="Tümü"
          active={activeId === "all"}
          count={products.length}
          onClick={() => setActiveId("all")}
        />
        {categories.map((c) => (
          <CategoryTab
            key={c._id}
            label={c.name}
            active={activeId === c._id}
            count={productsByCategory[c._id]?.length ?? 0}
            onClick={() => setActiveId(c._id)}
          />
        ))}
      </div>

      {/* Grid */}
      <AnimatePresence mode="wait">
        <motion.div
          key={`${activeId}-${trimmedQuery}`}
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: -12 }}
          transition={{ duration: 0.25 }}
        >
          {filtered.length === 0 ? (
            <div className="glass rounded-2xl p-12 text-center">
              {trimmedQuery ? (
                <>
                  <SearchX className="w-10 h-10 mx-auto text-brand-400 mb-3" />
                  <p className="text-brand-200 font-semibold">
                    “{trimmedQuery}” için sonuç bulunamadı
                  </p>
                  <p className="text-brand-400 text-sm mt-1">
                    Farklı bir arama veya kategori deneyin.
                  </p>
                </>
              ) : (
                <>
                  <LayoutGrid className="w-10 h-10 mx-auto text-brand-400 mb-3" />
                  <p className="text-brand-300">
                    Bu kategoride henüz ürün yok.
                  </p>
                </>
              )}
            </div>
          ) : (
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
              {filtered.map((p) => (
                <ProductCard key={p._id} product={p} />
              ))}
            </div>
          )}
        </motion.div>
      </AnimatePresence>
    </div>
  );
}

function CategoryTab({
  label,
  active,
  count,
  onClick,
}: {
  label: string;
  active: boolean;
  count: number;
  onClick: () => void;
}) {
  return (
    <button
      onClick={onClick}
      className={`px-4 py-2 rounded-full text-sm font-medium transition-all border ${
        active
          ? "bg-gradient-to-r from-brand-600 to-brand-500 text-white border-brand-400 shadow-lg shadow-brand-700/30"
          : "bg-brand-900/40 text-brand-200 border-brand-700/30 hover:border-brand-400/50 hover:text-white"
      }`}
    >
      {label}
      <span
        className={`ml-2 text-[10px] px-1.5 py-0.5 rounded-md ${
          active ? "bg-white/20" : "bg-brand-700/40"
        }`}
      >
        {count}
      </span>
    </button>
  );
}
