"use client";

import Link from "next/link";
import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import type { Category, Feature } from "@/lib/types";

export function FeaturesClient({
  features,
  categories,
}: {
  features: Feature[];
  categories: Category[];
}) {
  const router = useRouter();
  const [query, setQuery] = useState("");
  const [categoryId, setCategoryId] = useState("all");
  const [busyId, setBusyId] = useState<string | null>(null);

  const categoryMap = useMemo(
    () => new Map(categories.map((c) => [c.id, c.name])),
    [categories]
  );

  const filtered = features
    .filter((f) => (categoryId === "all" ? true : f.categoryId === categoryId))
    .filter((f) => {
      const q = query.trim().toLowerCase();
      if (!q) return true;
      return (
        f.name.toLowerCase().includes(q) ||
        f.description.toLowerCase().includes(q) ||
        f.businessBenefit.toLowerCase().includes(q)
      );
    })
    .sort((a, b) => a.sortOrder - b.sortOrder || a.name.localeCompare(b.name));

  async function duplicate(id: string) {
    setBusyId(id);
    try {
      const res = await fetch(`/api/features/${id}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "duplicate" }),
      });
      if (!res.ok) throw new Error("Duplicate failed");
      const copy = (await res.json()) as Feature;
      router.push(`/features/${copy.id}`);
      router.refresh();
    } finally {
      setBusyId(null);
    }
  }

  async function remove(id: string, name: string) {
    if (!confirm(`Delete “${name}”? This cannot be undone.`)) return;
    setBusyId(id);
    try {
      const res = await fetch(`/api/features/${id}`, { method: "DELETE" });
      if (!res.ok) throw new Error("Delete failed");
      router.refresh();
    } finally {
      setBusyId(null);
    }
  }

  return (
    <div className="space-y-5">
      <div className="flex flex-wrap items-end justify-between gap-3">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight text-[var(--ink)]">
            Features
          </h1>
          <p className="mt-1 text-sm text-[var(--muted)]">
            {features.length} total · Add, edit, duplicate, or delete
          </p>
        </div>
        <Link href="/features/new" className="btn-primary">
          Add feature
        </Link>
      </div>

      <div className="flex flex-wrap gap-3">
        <input
          className="input max-w-sm"
          placeholder="Search features…"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
        />
        <select
          className="input max-w-xs"
          value={categoryId}
          onChange={(e) => setCategoryId(e.target.value)}
        >
          <option value="all">All categories</option>
          {categories.map((c) => (
            <option key={c.id} value={c.id}>
              {c.name}
            </option>
          ))}
        </select>
      </div>

      <div className="panel overflow-hidden">
        <table className="w-full text-left text-sm">
          <thead className="border-b border-[var(--line)] bg-[var(--wash)] text-[var(--muted)]">
            <tr>
              <th className="px-4 py-3 font-medium">Name</th>
              <th className="hidden px-4 py-3 font-medium md:table-cell">
                Category
              </th>
              <th className="hidden px-4 py-3 font-medium sm:table-cell">
                Screenshots
              </th>
              <th className="px-4 py-3 font-medium">Actions</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map((feature) => (
              <tr
                key={feature.id}
                className="border-b border-[var(--line)] last:border-0"
              >
                <td className="px-4 py-3">
                  <div className="font-medium text-[var(--ink)]">
                    <Link
                      href={`/features/${feature.id}`}
                      className="hover:underline"
                    >
                      {feature.name}
                    </Link>
                  </div>
                  {feature.isDemo && (
                    <span className="mt-1 inline-block rounded bg-amber-100 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-amber-800">
                      Demo example
                    </span>
                  )}
                </td>
                <td className="hidden px-4 py-3 text-[var(--muted)] md:table-cell">
                  {categoryMap.get(feature.categoryId) ?? "—"}
                </td>
                <td className="hidden px-4 py-3 text-[var(--muted)] sm:table-cell">
                  {feature.screenshots.length}
                </td>
                <td className="px-4 py-3">
                  <div className="flex flex-wrap gap-2">
                    <Link
                      href={`/features/${feature.id}`}
                      className="text-[var(--accent)] hover:underline"
                    >
                      Edit
                    </Link>
                    <Link
                      href={`/preview/${feature.id}`}
                      className="text-[var(--muted)] hover:text-[var(--ink)]"
                    >
                      Preview
                    </Link>
                    <button
                      type="button"
                      disabled={busyId === feature.id}
                      onClick={() => duplicate(feature.id)}
                      className="text-[var(--muted)] hover:text-[var(--ink)] disabled:opacity-50"
                    >
                      Duplicate
                    </button>
                    <button
                      type="button"
                      disabled={busyId === feature.id}
                      onClick={() => remove(feature.id, feature.name)}
                      className="text-[var(--danger)] disabled:opacity-50"
                    >
                      Delete
                    </button>
                  </div>
                </td>
              </tr>
            ))}
            {filtered.length === 0 && (
              <tr>
                <td
                  colSpan={4}
                  className="px-4 py-10 text-center text-[var(--muted)]"
                >
                  No features match your filters.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
