<template>
  <div>
    <!-- Header -->
    <div class="flex justify-between items-center mb-6">
      <div>
        <h1 class="text-2xl font-bold text-primary-600">จัดการหมวดหมู่</h1>
        <p class="text-gray-600 mt-1">จัดการหมวดหมู่หลักสูตรในระบบ</p>
      </div>
      <q-btn
        color="primary"
        label="+ เพิ่มหมวดหมู่ใหม่"
        @click="openAddModal"
      />
    </div>

    <!-- Table Card -->
    <div class="bg-white rounded-xl shadow-sm p-6">
      <h2 class="text-lg font-semibold text-primary-600 mb-4">รายการหมวดหมู่</h2>
      
      <!-- Search -->
      <div class="mb-4" style="max-width: 400px">
        <q-input
          v-model="searchQuery"
          placeholder="ค้นหาหมวดหมู่..."
          outlined
          dense
          bg-color="grey-1"
          hide-bottom-space
        >
          <template v-slot:prepend>
            <q-icon name="search" />
          </template>
        </q-input>
      </div>

      <!-- Table -->
      <q-table
        :rows="filteredCategories"
        :columns="columns"
        row-key="id"
        :loading="loading"
        flat
        bordered
      >
        <!-- Name -->
        <template v-slot:body-cell-name="props">
          <q-td :props="props">
            <div class="font-medium">{{ props.row.name.th }}</div>
          </q-td>
        </template>

        <!-- Description -->
        <template v-slot:body-cell-description="props">
          <q-td :props="props">
            <div class="text-gray-600">{{ props.row.description.th }}</div>
          </q-td>
        </template>

        <!-- Date -->
        <template v-slot:body-cell-created_at="props">
          <q-td :props="props">
            {{ formatDate(props.row.created_at) }}
          </q-td>
        </template>

        <!-- Actions -->
        <template v-slot:body-cell-actions="props">
          <q-td :props="props">
            <div class="flex gap-2">
              <q-btn
                flat
                round
                dense
                icon="edit"
                color="warning"
                @click="openEditModal(props.row)"
              />
              <q-btn
                flat
                round
                dense
                icon="delete"
                color="negative"
                @click="confirmDelete(props.row)"
              />
            </div>
          </q-td>
        </template>
      </q-table>
    </div>

    <!-- Add/Edit Modal -->
    <q-dialog v-model="showModal" persistent>
      <q-card style="min-width: 500px">
        <q-card-section class="row items-center q-pb-none">
          <div class="text-h6">{{ isEditing ? 'แก้ไขหมวดหมู่' : 'เพิ่มหมวดหมู่ใหม่' }}</div>
          <q-space />
          <q-btn icon="close" flat round dense @click="showModal = false" />
        </q-card-section>

        <q-card-section>
          <q-form @submit="handleSave">
            <div class="grid grid-cols-2 gap-4 mb-4">
              <q-input
                v-model="form.name.th"
                label="ชื่อ (ภาษาไทย)"
                outlined
                :rules="[val => !!val || 'กรุณากรอกชื่อ']"
                lazy-rules="ondemand"
                hide-bottom-space
              />
              <q-input
                v-model="form.name.en"
                label="ชื่อ (English)"
                outlined
                :rules="[val => !!val || 'Please enter name']"
                lazy-rules="ondemand"
                hide-bottom-space
              />
            </div>

            <q-input
              v-model="form.slug"
              label="Slug (URL)"
              outlined
              class="mb-4"
              hint="ใช้สำหรับ URL เช่น web-development"
              :rules="[val => !!val || 'กรุณากรอก slug']"
              lazy-rules="ondemand"
              hide-bottom-space
            />

            <q-input
              v-model="form.description.th"
              label="คำอธิบาย (ภาษาไทย)"
              type="textarea"
              outlined
              class="mb-4"
              autogrow
            />

            <q-input
              v-model="form.description.en"
              label="คำอธิบาย (English)"
              type="textarea"
              outlined
              class="mb-4"
              autogrow
            />

            <div class="flex justify-end gap-2 mt-4">
              <q-btn
                flat
                label="ยกเลิก"
                color="grey-7"
                @click="showModal = false"
              />
              <q-btn
                type="submit"
                :label="isEditing ? 'บันทึก' : 'เพิ่ม'"
                color="primary"
                :loading="saving"
              />
            </div>
          </q-form>
        </q-card-section>
      </q-card>
    </q-dialog>
  </div>
</template>

<script setup lang="ts">
import { useQuasar } from 'quasar';
import { adminService, type CategoryResponse } from '~/services/admin.service';

definePageMeta({
  layout: 'admin',
  middleware: ['auth', 'admin']
});

const $q = useQuasar();
const authStore = useAuthStore();

// Data
const categories = ref<CategoryResponse[]>([]);
const loading = ref(true);
const searchQuery = ref('');
const showModal = ref(false);
const isEditing = ref(false);
const saving = ref(false);
const editingId = ref<number | null>(null);

// Form
const form = ref({
  name: { th: '', en: '' },
  slug: '',
  description: { th: '', en: '' }
});

// Table columns
const columns = [
  { name: 'id', label: 'ID', field: 'id', align: 'center' as const, style: 'width: 60px' },
  { name: 'name', label: 'ชื่อหมวดหมู่', field: 'name', align: 'left' as const },
  { name: 'description', label: 'คำอธิบาย', field: 'description', align: 'left' as const },
  { name: 'created_at', label: 'วันที่สร้าง', field: 'created_at', align: 'center' as const },
  { name: 'actions', label: 'การจัดการ', field: 'actions', align: 'center' as const, style: 'width: 120px' }
];

// Computed
const filteredCategories = computed(() => {
  if (!searchQuery.value) return categories.value;
  const query = searchQuery.value.toLowerCase();
  return categories.value.filter(cat =>
    cat.name.th.toLowerCase().includes(query) ||
    cat.name.en.toLowerCase().includes(query)
  );
});

// Methods
const fetchCategories = async () => {
  loading.value = true;
  try {
    categories.value = await adminService.getCategories();
  } catch (error) {
    $q.notify({
      type: 'negative',
      message: (error as any).data?.message || 'ไม่สามารถโหลดข้อมูลหมวดหมู่ได้',
      position: 'top'
    });
  } finally {
    loading.value = false;
  }
};

const formatDate = (date: string) => {
  return new Date(date).toLocaleDateString('th-TH', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
};

const resetForm = () => {
  form.value = {
    name: { th: '', en: '' },
    slug: '',
    description: { th: '', en: '' }
  };
  editingId.value = null;
  isEditing.value = false;
};

const openAddModal = () => {
  resetForm();
  showModal.value = true;
};

const openEditModal = (category: CategoryResponse) => {
  isEditing.value = true;
  editingId.value = category.id;
  form.value = {
    name: { ...category.name },
    slug: category.slug,
    description: { ...category.description }
  };
  showModal.value = true;
};

const handleSave = async () => {
  saving.value = true;
  try {
    if (isEditing.value && editingId.value) {
      const response = await adminService.updateCategory(editingId.value, {
        id: editingId.value,
        ...form.value
      });
      $q.notify({
        type: 'positive',
        message: response.message || 'แก้ไขหมวดหมู่สำเร็จ',
        position: 'top'
      });
    } else {
      const response = await adminService.createCategory({
        ...form.value,
        created_by: parseInt(authStore.user?.id || '0')
      });
      $q.notify({
        type: 'positive',
        message: response.message || 'เพิ่มหมวดหมู่สำเร็จ',
        position: 'top'
      });
    }
    showModal.value = false;
    fetchCategories();
  } catch (error: any) {
    $q.notify({
      type: 'negative',
      message: error.data?.message || 'เกิดข้อผิดพลาด กรุณาลองใหม่',
      position: 'top'
    });
  } finally {
    saving.value = false;
  }
};

const confirmDelete = (category: CategoryResponse) => {
  $q.dialog({
    title: 'ยืนยันการลบ',
    message: `คุณต้องการลบหมวดหมู่ "${category.name.th}" หรือไม่?`,
    cancel: true,
    persistent: true
  }).onOk(async () => {
    try {
      const response = await adminService.deleteCategory(category.id);
      $q.notify({
        type: 'positive',
        message: response.message || 'ลบหมวดหมู่สำเร็จ',
        position: 'top'
      });
      fetchCategories();
    } catch (error: any) {
      $q.notify({
        type: 'negative',
        message: error.data?.message || 'เกิดข้อผิดพลาดในการลบ',
        position: 'top'
      });
    }
  });
};

// Lifecycle
onMounted(() => {
  fetchCategories();
});
</script>
