"use client";

import { useMemo, useState } from "react";
import Link from "next/link";

type Manufacturer = {
  slug: string;
  company_name: string;
  bio: string | null;
  logo_url: string | null;
  categories: string[] | null;
  exhibits_nab: boolean;
  exhibits_ibc: boolean;
  shows_attending: string[] | null;
  mention_count: number;
  featured: boolean;
};

type ShowOption = {
  slug: string;
  short_name: string | null;
  name: string;
  start_date: string;
  end_date: string;
  status: string;
};

const LOGO_OVERRIDES: Record<string, string> = {
  "blackmagic-design": "/img/partners/blackmagic-design.png",
};

function resolveLogoUrl(slug: string, logoUrl: string | null): string | null {
  return LOGO_OVERRIDES[slug] || logoUrl || null;
}

export default function ManufacturerDirectoryClient({
  manufacturers,
  shows = [],
}: {
  manufacturers: Manufacturer[];
  shows?: ShowOption[];
}) {
  const [q, setQ] = useState("");
  // showFilter is now a show slug from bb.events (e.g. 'nab-show-2026') or
  // 'all' / 'both-major' (NAB+IBC overlap).
  const [showFilter, setShowFilter] = useState<string>("all");
  const [letter, setLetter] = useState<string>("All");

  // Per-show exhibitor counts for badge display + auto-hiding empty shows.
  const showCounts = useMemo(() => {
    const counts: Record<string, number> = {};
    for (const m of manufacturers) {
      for (const s of m.shows_attending || []) {
        counts[s] = (counts[s] || 0) + 1;
      }
    }
    return counts;
  }, [manufacturers]);

  const filtered = useMemo(() => {
    const needle = q.trim().toLowerCase();
    return manufacturers.filter((m) => {
      if (needle) {
        const hay = `${m.company_name} ${m.bio || ""}`.toLowerCase();
        if (!hay.includes(needle)) return false;
      }
      if (showFilter === "both-major") {
        if (!(m.exhibits_nab && m.exhibits_ibc)) return false;
      } else if (showFilter !== "all") {
        if (!(m.shows_attending || []).includes(showFilter)) return false;
      }
      if (letter !== "All") {
        const c = (m.company_name || "").trim().charAt(0).toUpperCase();
        if (letter === "#") {
          if (/^[A-Z]/.test(c)) return false;
        } else if (c !== letter) {
          return false;
        }
      }
      return true;
    });
  }, [manufacturers, q, showFilter, letter]);

  const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");

  return (
    <div>
      <div className="bg-white border border-[#DCE6F2] rounded-xl p-4 mb-6 flex flex-col gap-3 md:flex-row md:items-center md:gap-4">
        <div className="flex-1 min-w-0">
          <input
            type="search"
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="Search by company or product…"
            className="w-full bg-[#F8FAFC] border border-[#DCE6F2] rounded-md px-3 py-2 text-sm text-[#0F172A] placeholder:text-[#94A3B8] focus:outline-none focus:ring-2 focus:ring-[#1D4ED8]/40"
          />
        </div>
      </div>

      {/* Per-show filter chips. Every event from bb.events shows up; ones
          without exhibitor mappings yet render a "(soon)" badge so the
          admin can see what's still missing data. */}
      <div className="flex flex-wrap gap-1.5 mb-4">
        <button
          type="button"
          onClick={() => setShowFilter("all")}
          className={`px-3 py-1.5 rounded text-xs font-semibold ${
            showFilter === "all" ? "bg-[#1D4ED8] text-white" : "bg-white border border-[#DCE6F2] text-[#475569] hover:bg-[#F8FAFC]"
          }`}
        >
          All shows <span className="ml-1 opacity-60">({manufacturers.length.toLocaleString()})</span>
        </button>
        {shows.map((s) => {
          const count = showCounts[s.slug] || 0;
          const active = showFilter === s.slug;
          const label = s.short_name || s.name;
          return (
            <button
              key={s.slug}
              type="button"
              onClick={() => setShowFilter(s.slug)}
              className={`px-3 py-1.5 rounded text-xs font-semibold ${
                active ? "bg-[#1D4ED8] text-white" : "bg-white border border-[#DCE6F2] text-[#475569] hover:bg-[#F8FAFC]"
              }`}
              title={`${s.name} · ${s.start_date}${count === 0 ? " · exhibitor list coming soon" : ""}`}
            >
              {label}
              {count > 0 ? (
                <span className="ml-1 opacity-60">({count})</span>
              ) : (
                <span className="ml-1 text-amber-700 text-[10px]">soon</span>
              )}
            </button>
          );
        })}
      </div>

      <nav className="flex flex-wrap gap-1 mb-6 text-xs">
        {(["All", "#", ...letters] as const).map((l) => (
          <button
            key={l}
            type="button"
            onClick={() => setLetter(l)}
            className={`min-w-[28px] h-7 px-1.5 rounded font-semibold ${
              letter === l
                ? "bg-[#1D4ED8] text-white"
                : "bg-white border border-[#DCE6F2] text-[#475569] hover:bg-[#F8FAFC]"
            }`}
          >
            {l}
          </button>
        ))}
      </nav>

      <p className="text-xs text-[#888] mb-3">
        Showing {filtered.length.toLocaleString()} of {manufacturers.length.toLocaleString()} manufacturers
      </p>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
        {filtered.map((m) => (
          <Link
            key={m.slug}
            href={`/manufacturers/${m.slug}`}
            className="group bg-white border border-[#DCE6F2] rounded-xl p-4 hover:border-[#1D4ED8] hover:shadow-sm transition-all flex gap-3"
          >
            <div className="w-14 h-14 rounded-lg bg-[#FFFFFF] flex items-center justify-center overflow-hidden flex-shrink-0">
              {resolveLogoUrl(m.slug, m.logo_url) ? (
                /* eslint-disable-next-line @next/next/no-img-element */
                <img
                  src={resolveLogoUrl(m.slug, m.logo_url)!}
                  alt={`${m.company_name} logo`}
                  className="w-full h-full object-contain p-1"
                  loading="lazy"
                />
              ) : (
                <span className="text-[#666] text-lg font-semibold">
                  {(m.company_name || "?").trim().charAt(0).toUpperCase()}
                </span>
              )}
            </div>
            <div className="min-w-0 flex-1">
              <h3 className="font-semibold text-[#0F172A] truncate group-hover:text-[#1D4ED8] transition-colors">
                {m.company_name}
              </h3>
              <div className="flex items-center gap-1.5 mt-1 mb-1.5 flex-wrap">
                {(m.shows_attending || []).slice(0, 3).map((slug) => {
                  const ev = shows.find((s) => s.slug === slug);
                  if (!ev) return null;
                  return (
                    <span key={slug} className="text-[10px] font-semibold uppercase tracking-wider bg-[#1D4ED8]/10 text-[#1D4ED8] px-1.5 py-0.5 rounded">
                      {ev.short_name || ev.name}
                    </span>
                  );
                })}
                {m.featured && (
                  <span className="text-[10px] font-semibold uppercase tracking-wider bg-amber-50 text-amber-700 px-1.5 py-0.5 rounded">
                    Featured
                  </span>
                )}
              </div>
              <p className="text-xs text-[#64748B] line-clamp-2">
                {m.bio || "Profile coming soon."}
              </p>
            </div>
          </Link>
        ))}
      </div>

      {filtered.length === 0 && (
        <div className="text-center py-12 text-[#888] text-sm">
          No manufacturers match these filters.
        </div>
      )}
    </div>
  );
}
