import { prisma } from '@peyzajart/db'
import Link from 'next/link'
import AdminProductToggle from '../../../components/AdminProductToggle'
import { formatTL } from '../../../lib/format'

export const dynamic = 'force-dynamic'

export default async function AdminProductsPage() {
  const products = await prisma.product.findMany({
    orderBy: [{ category: 'asc' }, { nameTr: 'asc' }],
  })

  return (
    <div className="p-6 md:p-8">
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="font-display text-4xl font-light text-brown">Ürünler</h1>
          <p className="font-body text-sm text-brown/50 mt-1">{products.length} ürün</p>
        </div>
        <Link
          href="/admin/products/new"
          className="px-5 py-2 rounded-lg bg-brown text-cream font-body text-sm tracking-widest uppercase hover:bg-earth transition-colors"
        >
          + Yeni Ürün
        </Link>
      </div>

      <div className="bg-white shadow-sm rounded-xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="bg-sand/50 text-left">
                {['İsim', 'Kategori', 'Boyut', 'B2B Fiyat', 'Vitrin', 'Stok', 'Durum', ''].map(h => (
                  <th key={h} className="px-5 py-3 font-body text-xs text-brown/50 tracking-widest uppercase whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-sand">
              {products.map((p) => (
                <tr key={p.id} className="hover:bg-sand/20 transition-colors">
                  <td className="px-5 py-3">
                    <p className="font-body text-sm font-medium text-brown">{p.nameTr}</p>
                    <p className="font-body text-xs text-brown/40">{p.nameEn}</p>
                  </td>
                  <td className="px-5 py-3 font-body text-xs text-brown/60">{p.category}</td>
                  <td className="px-5 py-3 font-body text-xs text-brown/60">{p.size ?? '—'}</td>
                  <td className="px-5 py-3 font-body text-sm text-brown">{formatTL(p.priceB2B)}</td>
                  <td className="px-5 py-3 font-body text-sm text-brown/60">{formatTL(p.priceSelf)}</td>
                  <td className="px-5 py-3 font-body text-sm text-brown">{p.stock}</td>
                  <td className="px-5 py-3">
                    <AdminProductToggle id={p.id} isActive={p.isActive} />
                  </td>
                  <td className="px-5 py-3">
                    <Link
                      href={`/admin/products/${p.id}/edit`}
                      className="font-body text-xs text-earth hover:text-brown transition-colors"
                    >
                      Düzenle
                    </Link>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}
