---
import { getDb } from '../../../db/config';
import schema from '../../../db/schema';
import { desc } from 'drizzle-orm';

const { ConsentLog } = schema.tables;
const db = getDb();
const ADMIN_PASSWORD = import.meta.env.ADMIN_PASSWORD || 'moreminimore';

let consents: typeof ConsentLog.$inferSelect[] = [];
let isAuthenticated = false;

const url = new URL(Astro.request.url);
const action = url.searchParams.get('action');

if (action === 'logout') {
  isAuthenticated = false;
  consents = [];
  throw Astro.redirect('/admin/consent-logs');
}

if (Astro.request.method === 'POST') {
  const formData = await Astro.request.formData();
  const password = formData.get('password');

  if (password === ADMIN_PASSWORD) {
    isAuthenticated = true;
    consents = await db.select().from(ConsentLog).orderBy(desc(ConsentLog.timestamp)).limit(100);
    throw Astro.redirect('/admin/consent-logs');
  } else {
    isAuthenticated = false;
  }
} else if (isAuthenticated) {
  consents = await db.select().from(ConsentLog).orderBy(desc(ConsentLog.timestamp)).limit(100);
}
---

<!doctype html>
<html lang="th">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Admin - Consent Logs</title>
    <script src="https://cdn.tailwindcss.com"></script>
  </head>
  <body class="bg-gray-100 min-h-screen">
    {isAuthenticated ? (
      <div class="container mx-auto px-4 py-8">
        <div class="flex justify-between items-center mb-8">
          <h1 class="text-3xl font-bold text-gray-900">บันทึกความยินยอม (Consent Logs)</h1>
          <a href="/admin/consent-logs?action=logout" class="text-red-600 hover:underline">ออกจากระบบ</a>
        </div>

        <div class="bg-white rounded-lg shadow mb-6 p-6">
          <div class="grid md:grid-cols-4 gap-4">
            <div class="bg-blue-50 p-4 rounded-lg">
              <div class="text-sm text-gray-600">ทั้งหมด</div>
              <div class="text-2xl font-bold text-blue-600">{consents.length}</div>
            </div>
            <div class="bg-green-50 p-4 rounded-lg">
              <div class="text-sm text-gray-600">ยินยอม Analytics</div>
              <div class="text-2xl font-bold text-green-600">{consents.filter(c => c.analytics).length}</div>
            </div>
            <div class="bg-purple-50 p-4 rounded-lg">
              <div class="text-sm text-gray-600">ยินยอม Marketing</div>
              <div class="text-2xl font-bold text-purple-600">{consents.filter(c => c.marketing).length}</div>
            </div>
            <div class="bg-gray-50 p-4 rounded-lg">
              <div class="text-sm text-gray-600">นโยบายเวอร์ชัน</div>
              <div class="text-2xl font-bold text-gray-600">1.0</div>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-lg shadow overflow-hidden">
          <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
              <thead class="bg-gray-50">
                <tr>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">วันที่</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Session ID</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Essential</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Analytics</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Marketing</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">IP Hash</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ดำเนินการ</th>
                </tr>
              </thead>
              <tbody class="bg-white divide-y divide-gray-200">
                {consents.map((consent) => (
                  <tr class="hover:bg-gray-50">
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                      {new Date(consent.timestamp).toLocaleString('th-TH')}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 font-mono">
                      {consent.sessionId.substring(0, 8)}...
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                      <span class="px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">
                        {consent.essential ? '✓' : '✗'}
                      </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                      <span class={`px-2 py-1 text-xs font-semibold rounded-full ${consent.analytics ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
                        {consent.analytics ? '✓' : '✗'}
                      </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                      <span class={`px-2 py-1 text-xs font-semibold rounded-full ${consent.marketing ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
                        {consent.marketing ? '✓' : '✗'}
                      </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 font-mono">
                      {consent.ipHash || '-'}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm">
                      <button 
                        onclick={`deleteConsent('${consent.sessionId}')`}
                        class="text-red-600 hover:text-red-900 hover:underline"
                      >
                        ลบ
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        <div class="mt-6 text-sm text-gray-600">
          <p>แสดง {consents.length} รายการล่าสุด</p>
        </div>
      </div>
    ) : (
      <div class="min-h-screen flex items-center justify-center">
        <div class="bg-white p-8 rounded-lg shadow-lg max-w-md w-full">
          <h1 class="text-2xl font-bold text-gray-900 mb-6 text-center">เข้าสู่ระบบ Admin</h1>
          <form method="post" class="space-y-6">
            <div>
              <label for="password" class="block text-sm font-medium text-gray-700 mb-2">รหัสผ่าน</label>
              <input 
                type="password" 
                id="password" 
                name="password" 
                required
                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secondary focus:border-transparent"
                placeholder="กรอกรหัสผ่าน"
              />
            </div>
            <button 
              type="submit" 
              class="w-full bg-secondary text-white py-3 rounded-lg hover:bg-secondary-hover transition font-medium"
            >
              เข้าสู่ระบบ
            </button>
          </form>
          <p class="mt-4 text-sm text-gray-600 text-center">
            สำหรับจัดการบันทึกความยินยอมคุกกี้
          </p>
        </div>
      </div>
    )}

    <script>
      async function deleteConsent(sessionId: string) {
        if (!confirm('ต้องการลบรายการนี้หรือไม่? การกระทำนี้ไม่สามารถย้อนกลับได้')) {
          return;
        }

        try {
          const response = await fetch(`/api/consent/${sessionId}`, {
            method: 'DELETE'
          });

          if (response.ok) {
            window.location.reload();
          } else {
            alert('เกิดข้อผิดพลาดในการลบ');
          }
        } catch (error) {
          console.error('Delete error:', error);
          alert('เกิดข้อผิดพลาดในการลบ');
        }
      }
    </script>
  </body>
</html>
