"use client";

import { useState, useMemo } from "react";
import { Search, X } from "lucide-react";
import Link from "next/link";
import { formatCurrency, formatDate } from "@/lib/utils";

type Item = {
  id: string;
  productId: string;
  code: string;
  name: string;
  description: string;
  isActive: boolean;
  price: number;
  updatedAt: string;
};

export function VendorItemsTable({ items }: { items: Item[] }) {
  const [query, setQuery] = useState("");

  const filtered = useMemo(() => {
    const q = query.toLowerCase().trim();
    if (!q) return items;
    return items.filter(
      (item) =>
        item.name.toLowerCase().includes(q) ||
        item.code.toLowerCase().includes(q) ||
        item.description.toLowerCase().includes(q)
    );
  }, [items, query]);

  return (
    <div className="rounded-lg border border-neutral-200 bg-white p-6">
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-sm font-semibold text-neutral-900">
          Items Supplied
          <span className="ml-2 text-neutral-400 font-normal">({filtered.length}{query ? ` of ${items.length}` : ""})</span>
        </h2>
        {/* Search */}
        <div className="relative w-60">
          <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-neutral-400" />
          <input
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Search items…"
            className="w-full rounded-lg border border-neutral-200 py-1.5 pl-8 pr-8 text-sm focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20"
          />
          {query && (
            <button onClick={() => setQuery("")} className="absolute right-2.5 top-1/2 -translate-y-1/2 text-neutral-400 hover:text-neutral-600">
              <X className="h-3.5 w-3.5" />
            </button>
          )}
        </div>
      </div>

      {items.length === 0 ? (
        <p className="text-sm text-neutral-400 italic">
          No items on record yet. Items are added automatically when a PO with this vendor is marked as paid.
        </p>
      ) : filtered.length === 0 ? (
        <p className="text-sm text-neutral-400 italic py-4 text-center">No items match "{query}"</p>
      ) : (
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-neutral-200">
              <th className="pb-2 text-left font-medium text-neutral-600">Item</th>
              <th className="pb-2 text-left font-medium text-neutral-600 pl-4 whitespace-nowrap">Code</th>
              <th className="pb-2 text-right font-medium text-neutral-600 pl-4 whitespace-nowrap">Last Price</th>
              <th className="pb-2 text-right font-medium text-neutral-600 pl-4 whitespace-nowrap">Updated</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-neutral-100">
            {filtered.map((item) => (
              <tr key={item.id} className="hover:bg-neutral-50">
                <td className="py-2.5 pr-4">
                  <Link href={`/admin/products/${item.productId}`} className="font-medium text-primary-600 hover:underline">
                    {item.name}
                  </Link>
                  {item.description && (
                    <span className="block text-xs text-neutral-500 mt-0.5 line-clamp-1">{item.description}</span>
                  )}
                  {!item.isActive && <span className="ml-1 text-xs text-neutral-400 italic">inactive</span>}
                </td>
                <td className="py-2.5 pl-4 font-mono text-xs text-neutral-500">{item.code}</td>
                <td className="py-2.5 pl-4 text-right font-medium text-neutral-900">{formatCurrency(item.price)}</td>
                <td className="py-2.5 pl-4 text-right text-neutral-500">{formatDate(new Date(item.updatedAt))}</td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </div>
  );
}
