'use client';

import Link from 'next/link';
import { useMemo, useState } from 'react';
import { formatPrice } from '@/lib/format';
import type { Category, Product } from '@/lib/types';

export default function ProductTable({
  products,
  categories,
}: {
  products: Product[];
  categories: Category[];
}) {
  const [query, setQuery] = useState('');
  const [cat, setCat] = useState('tumu');
  const byCat = useMemo(() => new Map(categories.map((c) => [c.id, c])), [categories]);

  const rows = useMemo(() => {
    const q = query.trim().toLocaleLowerCase('tr');
    const order = new Map(categories.map((c, i) => [c.id, i]));
    return products
      .filter((p) => {
        if (cat !== 'tumu' && p.category_id !== cat) return false;
        if (!q) return true;
        return p.name.toLocaleLowerCase('tr').includes(q);
      })
      .sort(
        (a, b) =>
          (order.get(a.category_id) ?? 99) - (order.get(b.category_id) ?? 99) ||
          a.sort_order - b.sort_order
      );
  }, [products, categories, query, cat]);

  return (
    <>
      <div className="flex flex-col gap-3 sm:flex-row">
        <input
          type="search"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="Ürün ara…"
          aria-label="Ürün ara"
          className="field flex-1"
        />
        <select
          value={cat}
          onChange={(e) => setCat(e.target.value)}
          aria-label="Kategoriye göre filtrele"
          className="field sm:w-56"
        >
          <option value="tumu">Tüm kategoriler</option>
          {categories.map((c) => (
            <option key={c.id} value={c.id}>
              {c.name}
            </option>
          ))}
        </select>
      </div>

      <p className="mt-4 text-xs uppercase tracking-wider text-cocoa-400">
        {rows.length} ürün
      </p>

      <div className="mt-3 overflow-hidden rounded-2xl border border-cocoa-800/10 bg-white">
        <table className="w-full text-sm">
          <thead className="bg-cream-100/70 text-left text-xs uppercase tracking-wider text-cocoa-400">
            <tr>
              <th className="px-5 py-3 font-medium">Ürün</th>
              <th className="hidden px-5 py-3 font-medium md:table-cell">Kategori</th>
              <th className="hidden px-5 py-3 font-medium sm:table-cell">Birim</th>
              <th className="px-5 py-3 font-medium">Fiyat</th>
              <th className="px-5 py-3 font-medium">Durum</th>
              <th className="px-5 py-3" />
            </tr>
          </thead>
          <tbody className="divide-y divide-cocoa-800/8">
            {rows.map((p) => (
              <tr key={p.id} className="transition-colors hover:bg-cream-50">
                <td className="px-5 py-3.5">
                  <span className="font-medium text-cocoa-800">{p.name}</span>
                  {p.is_featured && (
                    <span className="ml-2 rounded-full bg-gold-400/20 px-2 py-0.5 text-[0.62rem] uppercase tracking-wider text-gold-600">
                      öne çıkan
                    </span>
                  )}
                </td>
                <td className="hidden px-5 py-3.5 text-cocoa-500 md:table-cell">
                  {byCat.get(p.category_id)?.name ?? '—'}
                </td>
                <td className="hidden px-5 py-3.5 text-cocoa-500 sm:table-cell">{p.unit ?? '—'}</td>
                <td className="px-5 py-3.5 text-cocoa-700">{formatPrice(p.price) ?? '—'}</td>
                <td className="px-5 py-3.5">
                  <span
                    className={`inline-flex items-center gap-1.5 text-xs ${
                      p.is_active ? 'text-green-700' : 'text-cocoa-400'
                    }`}
                  >
                    <span
                      className={`h-1.5 w-1.5 rounded-full ${
                        p.is_active ? 'bg-green-600' : 'bg-cocoa-300'
                      }`}
                    />
                    {p.is_active ? 'Yayında' : 'Pasif'}
                  </span>
                </td>
                <td className="px-5 py-3.5 text-right">
                  <Link
                    href={`/admin/urunler/${encodeURIComponent(p.id)}`}
                    className="text-xs text-gold-600 hover:underline"
                  >
                    Düzenle
                  </Link>
                </td>
              </tr>
            ))}
            {rows.length === 0 && (
              <tr>
                <td colSpan={6} className="px-5 py-12 text-center text-sm text-cocoa-400">
                  Sonuç bulunamadı.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </>
  );
}
