---
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');

const { searchParams } = Astro.url;
const status = searchParams.get('status') || 'all';
const page = parseInt(searchParams.get('page') || '1');

// Fetch orders
let url = new URL('/api/vendors/orders', Astro.url);
url.searchParams.set('page', String(page));
url.searchParams.set('limit', '20');
if (status !== 'all') {
  url.searchParams.set('status', status);
}

const ordersRes = await fetch(url.toString(), {
  headers: { 'Authorization': `Bearer ${token}` }
});
const { orders, total } = await ordersRes.json();

// Status config
const statusConfig = {
  all: { label: 'ทั้งหมด', color: 'bg-gray-100 text-gray-700' },
  pending: { label: 'รอชำระเงิน', color: 'bg-yellow-100 text-yellow-700' },
  paid: { label: 'ชำระแล้ว', color: 'bg-blue-100 text-blue-700' },
  shipped: { label: 'จัดส่งแล้ว', color: 'bg-purple-100 text-purple-700' },
  delivered: { label: 'รับสินค้าแล้ว', color: 'bg-green-100 text-green-700' },
  cancelled: { label: 'ยกเลิก', color: 'bg-red-100 text-red-700' }
};
---

<Layout title="จัดการคำสั่งซื้อ">
  <div class="min-h-screen bg-gray-100">
    <Header />
    <div class="flex">
      <AdminSidebar client:load role="vendor" />
      <main class="flex-1 p-8">
        <h1 class="text-2xl font-bold mb-8">คำสั่งซื้อ</h1>
        
        <!-- Status Tabs -->
        <div class="flex gap-2 mb-6 overflow-x-auto pb-2">
          {Object.entries(statusConfig).map(([key, config]) => (
            <a 
              href={`/vendor/orders${key !== 'all' ? `?status=${key}` : ''}`}
              class={`px-4 py-2 rounded-lg whitespace-nowrap transition-colors ${
                status === key ? `${config.color} font-medium` : 'bg-white text-gray-600 hover:bg-gray-50'
              }`}
            >
              {config.label}
            </a>
          ))}
        </div>
        
        <!-- Orders Table -->
        {orders && orders.length > 0 ? (
          <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">
                {orders.map(order => (
                  <tr class="hover:bg-gray-50">
                    <td class="px-6 py-4 font-medium text-blue-600">{order.ref_no}</td>
                    <td class="px-6 py-4">
                      <p class="font-medium">{order.shipping_name}</p>
                      <p class="text-sm text-gray-500">{order.shipping_phone}</p>
                    </td>
                    <td class="px-6 py-4 font-medium">฿{order.total.toLocaleString()}</td>
                    <td class="px-6 py-4">
                      <span class={`px-2 py-1 rounded-full text-xs font-medium ${statusConfig[order.status]?.color || 'bg-gray-100 text-gray-700'}`}>
                        {statusConfig[order.status]?.label || order.status}
                      </span>
                    </td>
                    <td class="px-6 py-4 text-gray-500">
                      {new Date(order.created_at).toLocaleDateString('th-TH')}
                    </td>
                    <td class="px-6 py-4">
                      <button class="text-blue-600 hover:text-blue-800 font-medium view-order" data-order-id={order.id}>
                        ดูรายละเอียด
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div class="text-center py-20 bg-white rounded-xl">
            <p class="text-gray-500">ไม่พบคำสั่งซื้อ</p>
          </div>
        )}
      </main>
    </div>
  </div>
</Layout>
