"use client";

import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { Product } from "@/lib/types";
import { formatPrice } from "@/lib/format";
import { categories } from "@/lib/categories";

export function ProductsTable({ products }: { products: Product[] }) {
  const router = useRouter();
  const [deletingId, setDeletingId] = useState<string | null>(null);

  async function handleDelete(id: string, name: string) {
    if (!confirm(`Delete "${name}"? This can't be undone.`)) return;
    setDeletingId(id);
    try {
      const res = await fetch(`/api/admin/products/${id}`, { method: "DELETE" });
      if (res.ok) {
        router.refresh();
      } else {
        alert("Couldn't delete that product.");
      }
    } finally {
      setDeletingId(null);
    }
  }

  return (
    <div className="overflow-x-auto rounded-xl border border-black/[0.06]">
      <table className="w-full min-w-[700px] text-left text-sm">
        <thead className="border-b border-black/[0.06] bg-black/[0.015] text-xs uppercase text-black/45">
          <tr>
            <th className="px-4 py-3 font-medium">Product</th>
            <th className="px-4 py-3 font-medium">Category</th>
            <th className="px-4 py-3 font-medium">Price</th>
            <th className="px-4 py-3 font-medium">Stock</th>
            <th className="px-4 py-3 font-medium"></th>
          </tr>
        </thead>
        <tbody>
          {products.map((p) => (
            <tr key={p.id} className="border-b border-black/[0.04] last:border-0">
              <td className="px-4 py-3">
                <div className="flex items-center gap-3">
                  <div className="relative h-10 w-10 shrink-0 overflow-hidden rounded-lg bg-brand-cream">
                    <Image src={p.images[0]} alt="" fill sizes="40px" className="object-cover" />
                  </div>
                  <div>
                    <p className="font-medium text-brand-ink">{p.name}</p>
                    <p className="text-xs text-black/45">{p.sku}</p>
                  </div>
                </div>
              </td>
              <td className="px-4 py-3 text-black/65">
                {categories.find((c) => c.slug === p.category)?.name ?? p.category}
              </td>
              <td className="px-4 py-3 text-black/65">{formatPrice(p.price)}</td>
              <td className="px-4 py-3">
                <span className={p.stock <= 3 ? "font-medium text-brand-orange-dark" : "text-black/65"}>
                  {p.stock}
                </span>
              </td>
              <td className="px-4 py-3 text-right">
                <div className="flex justify-end gap-3">
                  <Link
                    href={`/admin/products/${p.id}`}
                    className="text-sm font-medium text-brand-ink hover:underline"
                  >
                    Edit
                  </Link>
                  <button
                    onClick={() => handleDelete(p.id, p.name)}
                    disabled={deletingId === p.id}
                    className="text-sm font-medium text-danger hover:underline disabled:opacity-50"
                  >
                    Delete
                  </button>
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
