<template>
  <div class="min-h-screen bg-gray-50">
    <Navbar />
    
    <div class="max-w-7xl mx-auto px-4 py-8">
      <div class="flex items-center justify-between mb-6">
        <h1 class="text-3xl font-bold text-gray-800">Categories</h1>
        <button @click="showAddModal = true" class="bg-orange-600 text-white px-6 py-3 rounded-lg font-semibold hover:bg-orange-700 transition">
          + Add Category
        </button>
      </div>

      <div v-if="loading" class="text-center py-12">
        <div class="text-gray-500">Loading...</div>
      </div>

      <div v-else class="bg-white rounded-xl shadow-sm overflow-hidden">
        <table class="w-full">
          <thead class="bg-gray-50 border-b">
            <tr>
              <th class="px-6 py-4 text-left text-sm font-semibold text-gray-700">ID</th>
              <th class="px-6 py-4 text-left text-sm font-semibold text-gray-700">Name</th>
              <th class="px-6 py-4 text-right text-sm font-semibold text-gray-700">Actions</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="category in categories" :key="category.id" class="border-b hover:bg-gray-50">
              <td class="px-6 py-4 text-gray-800">{{ category.id }}</td>
              <td class="px-6 py-4 text-gray-800 font-medium">{{ category.name }}</td>
              <td class="px-6 py-4 text-right">
                <button @click="editCategory(category)" class="text-blue-600 hover:text-blue-800 mr-4">Edit</button>
                <button @click="deleteCategory(category.id)" class="text-red-600 hover:text-red-800">Delete</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- Add/Edit Modal -->
    <div v-if="showAddModal || showEditModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" @click.self="closeModal">
      <div class="bg-white rounded-xl p-6 w-full max-w-md">
        <h3 class="text-xl font-bold mb-4">{{ showEditModal ? 'Edit Category' : 'Add Category' }}</h3>
        <input v-model="categoryName" type="text" placeholder="Category Name" class="w-full px-4 py-3 border rounded-lg mb-4 focus:ring-2 focus:ring-orange-500" />
        <div class="flex gap-3">
          <button @click="saveCategory" class="flex-1 bg-orange-600 text-white py-3 rounded-lg font-semibold hover:bg-orange-700">Save</button>
          <button @click="closeModal" class="flex-1 bg-gray-200 text-gray-700 py-3 rounded-lg font-semibold hover:bg-gray-300">Cancel</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import api from '../../services/api';
import Navbar from '../../components/Navbar.vue';

const loading = ref(true);
const categories = ref([]);
const showAddModal = ref(false);
const showEditModal = ref(false);
const categoryName = ref('');
const editingId = ref(null);

const loadCategories = async () => {
  try {
    loading.value = true;
    const response = await api.get('/manager/categories');
    categories.value = response.data;
  } catch (error) {
    console.error('Error loading categories:', error);
  } finally {
    loading.value = false;
  }
};

const saveCategory = async () => {
  if (!categoryName.value.trim()) {
    alert('Please enter category name');
    return;
  }

  try {
    if (showEditModal.value) {
      await api.put(`/manager/categories/${editingId.value}`, { name: categoryName.value });
    } else {
      await api.post('/manager/categories', { name: categoryName.value });
    }
    closeModal();
    loadCategories();
  } catch (error) {
    console.error('Error saving category:', error);
    alert('Failed to save category');
  }
};

const editCategory = (category) => {
  editingId.value = category.id;
  categoryName.value = category.name;
  showEditModal.value = true;
};

const deleteCategory = async (id) => {
  if (!confirm('Are you sure you want to delete this category?')) return;

  try {
    await api.delete(`/manager/categories/${id}`);
    loadCategories();
  } catch (error) {
    console.error('Error deleting category:', error);
    alert('Failed to delete category');
  }
};

const closeModal = () => {
  showAddModal.value = false;
  showEditModal.value = false;
  categoryName.value = '';
  editingId.value = null;
};

onMounted(() => {
  loadCategories();
});
</script>
