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

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

// Fetch order details
const orderRes = await fetch(new URL(`/api/orders/${id}`, Astro.url).toString(), {
  headers: { 'Authorization': `Bearer ${token}` }
});
const { order } = await orderRes.json();

if (!order) {
  return Astro.redirect('/account/orders');
}

// Status colors
const statusColors = {
  pending: 'bg-yellow-100 text-yellow-700',
  paid: 'bg-blue-100 text-blue-700',
  shipped: 'bg-purple-100 text-purple-700',
  delivered: 'bg-green-100 text-green-700',
  cancelled: 'bg-red-100 text-red-700'
};

const statusLabels = {
  pending: 'รอชำระเงิน',
  paid: 'ชำระแล้ว',
  shipped: 'จัดส่งแล้ว',
  delivered: 'รับสินค้าแล้ว',
  cancelled: 'ยกเลิก'
};

const paymentStatusLabels = {
  pending: 'รอชำระเงิน',
  paid: 'ชำระแล้ว',
  failed: 'ชำระไม่สำเร็จ',
  refunded: 'คืนเงินแล้ว'
};

const paymentStatusColors = {
  pending: 'bg-yellow-100 text-yellow-700',
  paid: 'bg-green-100 text-green-700',
  failed: 'bg-red-100 text-red-700',
  refunded: 'bg-gray-100 text-gray-700'
};
---

<Layout title={`คำสั่งซื้อ ${order.ref_no}`}>
  <Header />
  
  <div class="container mx-auto px-4 py-8">
    <!-- Breadcrumb -->
    <nav class="text-sm text-gray-500 mb-6">
      <a href="/" class="hover:text-blue-600">หน้าแรก</a>
      <span class="mx-2">/</span>
      <a href="/account" class="hover:text-blue-600">บัญชีของฉัน</a>
      <span class="mx-2">/</span>
      <a href="/account/orders" class="hover:text-blue-600">คำสั่งซื้อ</a>
      <span class="mx-2">/</span>
      <span class="text-gray-900">{order.ref_no}</span>
    </nav>
    
    <div class="flex justify-between items-center mb-8">
      <div>
        <h1 class="text-2xl font-bold">คำสั่งซื้อ {order.ref_no}</h1>
        <p class="text-gray-500">วันที่ {new Date(order.created_at).toLocaleDateString('th-TH', { year: 'numeric', month: 'long', day: 'numeric' })}</p>
      </div>
      <div class="flex gap-2">
        <span class={`px-4 py-2 rounded-full text-sm font-medium ${statusColors[order.status]}`}>
          {statusLabels[order.status]}
        </span>
        <span class={`px-4 py-2 rounded-full text-sm font-medium ${paymentStatusColors[order.payment_status]}`}>
          {paymentStatusLabels[order.payment_status]}
        </span>
      </div>
    </div>
    
    <div class="grid lg:grid-cols-3 gap-8">
      <!-- Order Items -->
      <div class="lg:col-span-2">
        <div class="bg-white rounded-xl shadow-sm overflow-hidden mb-6">
          <div class="p-6 border-b">
            <h2 class="font-bold">รายการสินค้า</h2>
          </div>
          <div class="divide-y">
            {order.items?.map(item => (
              <div class="p-6 flex gap-4">
                <div class="w-20 h-20 bg-gray-100 rounded-lg overflow-hidden flex-shrink-0">
                  <img src={item.image} alt={item.name} class="w-full h-full object-cover" />
                </div>
                <div class="flex-1">
                  <h3 class="font-medium">{item.name}</h3>
                  {item.variant && (
                    <p class="text-sm text-gray-500">{item.variant}</p>
                  )}
                  <div class="flex justify-between mt-2">
                    <span class="text-gray-500">x{item.quantity}</span>
                    <span class="font-medium">฿{(item.price * item.quantity).toLocaleString()}</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
        
        <!-- Shipping Info -->
        <div class="bg-white rounded-xl shadow-sm p-6">
          <h2 class="font-bold mb-4">ที่อยู่จัดส่ง</h2>
          <div class="text-gray-600">
            <p class="font-medium text-gray-900">{order.shipping_name}</p>
            <p>{order.shipping_phone}</p>
            <p>{order.shipping_address}</p>
            <p>{order.shipping_district}, {order.shipping_province} {order.shipping_postal}</p>
          </div>
          {order.tracking_number && (
            <div class="mt-4 p-4 bg-blue-50 rounded-lg">
              <p class="text-sm text-gray-500">หมายเลขติดตามพัสดุ</p>
              <p class="font-mono font-medium">{order.tracking_number}</p>
            </div>
          )}
        </div>
      </div>
      
      <!-- Summary -->
      <div>
        <div class="bg-white rounded-xl shadow-sm p-6 sticky top-24">
          <h2 class="font-bold mb-4">สรุปคำสั่งซื้อ</h2>
          <dl class="space-y-3 text-sm">
            <div class="flex justify-between">
              <dt class="text-gray-500">ยอดสินค้า</dt>
              <dd>฿{order.subtotal?.toLocaleString() || 0}</dd>
            </div>
            <div class="flex justify-between">
              <dt class="text-gray-500">ค่าจัดส่ง</dt>
              <dd>{order.shipping_fee === 0 ? 'ฟรี' : `฿${order.shipping_fee?.toLocaleString()}`}</dd>
            </div>
            {order.discount > 0 && (
              <div class="flex justify-between text-green-600">
                <dt>ส่วนลด</dt>
                <dd>-฿{order.discount?.toLocaleString()}</dd>
              </div>
            )}
            <hr />
            <div class="flex justify-between font-bold text-lg">
              <dt>ยอดรวม</dt>
              <dd class="text-blue-600">฿{order.total?.toLocaleString()}</dd>
            </div>
          </dl>
          
          {order.payment_status === 'pending' && (
            <div class="mt-6 space-y-3">
              <a 
                href={`/checkout/payment/${order.id}`}
                class="block w-full bg-blue-600 text-white py-3 px-4 rounded-lg text-center hover:bg-blue-700 transition-colors font-medium"
              >
                ชำระเงิน
              </a>
              <button 
                class="block w-full border border-red-300 text-red-600 py-3 px-4 rounded-lg text-center hover:bg-red-50 transition-colors"
                onclick="if(confirm('ยกเลิกคำสั่งซื้อนี้?')) { fetch('/api/orders/{order.id}/cancel', {method: 'POST', headers: {'Authorization': 'Bearer {token}'}}).then(() => location.reload()); }"
              >
                ยกเลิกคำสั่งซื้อ
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  </div>
  
  <Footer />
</Layout>
