---
import Layout from '../../layouts/Layout.astro';
import Header from '../../components/layout/Header';
import AdminSidebar from '../../components/admin/AdminSidebar';

const token = Astro.cookies.get('session')?.value;
if (!token) return Astro.redirect('/login');

// Check admin role
const meRes = await fetch(new URL('/api/auth/me', Astro.url).toString(), {
  headers: { 'Authorization': `Bearer ${token}` }
});
const { user } = await meRes.json();
if (user?.role !== 'admin') return Astro.redirect('/');

// Fetch vendors
const vendorsRes = await fetch(new URL('/api/admin/vendors', Astro.url).toString(), {
  headers: { 'Authorization': `Bearer ${token}` }
});
const { vendors } = await vendorsRes.json();

const statusColors = {
  active: 'bg-green-100 text-green-700',
  pending: 'bg-yellow-100 text-yellow-700',
  suspended: 'bg-red-100 text-red-700'
};

const statusLabels = {
  active: 'เปิดใช้งาน',
  pending: 'รออนุมัติ',
  suspended: 'ระงับ'
};
---

<Layout title="จัดการร้านค้า">
  <div class="min-h-screen bg-gray-100">
    <Header />
    <div class="flex">
      <AdminSidebar client:load role="admin" />
      <main class="flex-1 p-8">
        <h1 class="text-2xl font-bold mb-8">ร้านค้าทั้งหมด</h1>
        
        <!-- Pending Approval Alert -->
        {vendors?.filter(v => v.status === 'pending').length > 0 && (
          <div class="bg-yellow-50 border border-yellow-200 rounded-xl p-4 mb-6">
            <p class="text-yellow-800">
              มีร้านค้ารอการอนุมัติ {vendors.filter(v => v.status === 'pending').length} ร้าน
            </p>
          </div>
        )}
        
        <div class="bg-white rounded-xl shadow-sm overflow-hidden">
          <table class="w-full">
            <thead class="bg-gray-50">
              <tr>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">ร้านค้า</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">เจ้าของ</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">สถานะ</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">สินค้า</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">สมัครเมื่อ</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">จัดการ</th>
              </tr>
            </thead>
            <tbody class="divide-y divide-gray-200">
              {vendors?.map(vendor => (
                <tr class="hover:bg-gray-50">
                  <td class="px-6 py-4">
                    <div class="flex items-center gap-3">
                      <div class="w-12 h-12 bg-gray-100 rounded-lg overflow-hidden">
                        <img src={vendor.logo || '/store-placeholder.jpg'} alt="" class="w-full h-full object-cover" />
                      </div>
                      <div>
                        <p class="font-medium">{vendor.store_name}</p>
                        <p class="text-sm text-gray-500">/{vendor.store_slug}</p>
                      </div>
                    </div>
                  </td>
                  <td class="px-6 py-4">
                    <p>{vendor.user?.name}</p>
                    <p class="text-sm text-gray-500">{vendor.user?.email}</p>
                  </td>
                  <td class="px-6 py-4">
                    <span class={`px-2 py-1 rounded-full text-xs font-medium ${statusColors[vendor.status]}`}>
                      {statusLabels[vendor.status]}
                    </span>
                  </td>
                  <td class="px-6 py-4">{vendor.product_count || 0}</td>
                  <td class="px-6 py-4 text-gray-500">
                    {new Date(vendor.created_at).toLocaleDateString('th-TH')}
                  </td>
                  <td class="px-6 py-4">
                    <a href={`/vendors/${vendor.store_slug}`} target="_blank" class="text-blue-600 hover:text-blue-800 font-medium mr-3">
                      ดูร้าน
                    </a>
                    {vendor.status === 'pending' && (
                      <button class="text-green-600 hover:text-green-800 font-medium approve-vendor" data-id={vendor.id}>
                        อนุมัติ
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </main>
    </div>
  </div>
</Layout>
