<script setup lang="ts">
  import { ref, onMounted, computed } from "vue";
  import { useRouter } from "vue-router";
  import PageLayout from "@/components/PageLayout.vue";
  import {
    Card,
    CardHeader,
    CardTitle,
    CardContent,
  } from "@/components/ui/card";
  import { Button } from "@/components/ui/button";
  import { Input } from "@/components/ui/input";
  import { Label } from "@/components/ui/label";
  import { useCategoriesStore } from "@/stores/categories";
  import { useAuthStore } from "@/stores/auth";

  // Initialize stores and router
  const router = useRouter();
  const categoriesStore = useCategoriesStore();
  const authStore = useAuthStore();

  // Check if user is admin
  const isAdmin = computed(() => authStore.user?.role === "admin");

  // State
  const allCategories = ref<any[]>([]);
  const loading = ref(false);
  const error = ref("");
  const success = ref("");

  // Form state for creating/editing categories
  const showForm = ref(false);
  const editingCategory = ref<any>(null);
  const formData = ref({
    name: "",
    icon: "",
    color: "#3B82F6",
  });

  // Available icons
  const availableIcons = [
    "🍔",
    "🚗",
    "🏠",
    "🎬",
    "💰",
    "📦",
    "🛒",
    "💡",
    "🎯",
    "📱",
    "✈️",
    "🏥",
    "📚",
    "🎵",
    "👕",
    "⚽",
    "🍕",
    "☕",
    "🎮",
    "💊",
  ];

  // Available colors
  const availableColors = [
    "#3B82F6",
    "#EF4444",
    "#10B981",
    "#F59E0B",
    "#8B5CF6",
    "#EC4899",
    "#06B6D4",
    "#84CC16",
    "#F97316",
    "#6366F1",
  ];

  // Load all categories
  async function loadCategories() {
    if (!isAdmin.value) {
      error.value = "Admin access required";
      return;
    }

    loading.value = true;
    error.value = "";

    try {
      const categories = await categoriesStore.fetchAllCategories();
      allCategories.value = categories || [];
    } catch (err: any) {
      error.value = err.message;
    } finally {
      loading.value = false;
    }
  }

  // Create or update category
  async function saveCategory() {
    if (!formData.value.name.trim()) {
      error.value = "Category name is required";
      return;
    }

    loading.value = true;
    error.value = "";
    success.value = "";

    try {
      if (editingCategory.value) {
        // Update existing category
        await categoriesStore.updateCategory(editingCategory.value._id, {
          name: formData.value.name,
          icon: formData.value.icon,
          color: formData.value.color,
        });
        success.value = "Category updated successfully";
      } else {
        // Create new category
        await categoriesStore.createGlobalCategory({
          name: formData.value.name,
          icon: formData.value.icon,
          color: formData.value.color,
        });
        success.value = "Category created successfully";
      }

      resetForm();
      await loadCategories();
    } catch (err: any) {
      error.value = err.message;
    } finally {
      loading.value = false;
    }
  }

  // Delete category
  async function deleteCategory(categoryId: string) {
    if (
      !confirm(
        "Are you sure you want to delete this category? This action cannot be undone.",
      )
    ) {
      return;
    }

    loading.value = true;
    error.value = "";
    success.value = "";

    try {
      await categoriesStore.deleteCategory(categoryId);
      success.value = "Category deleted successfully";
      await loadCategories();
    } catch (err: any) {
      error.value = err.message;
    } finally {
      loading.value = false;
    }
  }

  // Edit category
  function editCategory(category: any) {
    editingCategory.value = category;
    formData.value = {
      name: category.name,
      icon: category.icon || "",
      color: category.color || "#3B82F6",
    };
    showForm.value = true;
  }

  // Reset form
  function resetForm() {
    editingCategory.value = null;
    formData.value = {
      name: "",
      icon: "",
      color: "#3B82F6",
    };
    showForm.value = false;
  }

  // Clear messages
  function clearMessages() {
    error.value = "";
    success.value = "";
  }

  // Load categories on mount
  onMounted(() => {
    if (!isAdmin.value) {
      router.push("/dashboard");
      return;
    }
    loadCategories();
  });
</script>

<template>
  <PageLayout header="Category Management (Admin)">
    <div class="max-w-6xl mx-auto space-y-6">
      <!-- Access Control -->
      <div v-if="!isAdmin" class="text-center py-8">
        <Card>
          <CardContent class="pt-6">
            <h2 class="text-xl font-bold text-red-600 mb-2">Access Denied</h2>
            <p class="text-gray-600">
              You need admin privileges to access this page.
            </p>
            <Button @click="router.push('/dashboard')" class="mt-4">
              Back to Dashboard
            </Button>
          </CardContent>
        </Card>
      </div>

      <!-- Admin Interface -->
      <div v-else>
        <!-- Messages -->
        <div
          v-if="error"
          class="mb-4 p-3 bg-red-50 border border-red-200 text-red-700 rounded">
          {{ error }}
          <button
            @click="clearMessages"
            class="ml-2 text-red-500 hover:text-red-700">
            ×
          </button>
        </div>

        <div
          v-if="success"
          class="mb-4 p-3 bg-green-50 border border-green-200 text-green-700 rounded">
          {{ success }}
          <button
            @click="clearMessages"
            class="ml-2 text-green-500 hover:text-green-700">
            ×
          </button>
        </div>

        <!-- Action Buttons -->
        <div class="flex justify-between items-center mb-6">
          <h1 class="text-2xl font-bold text-gray-900">Category Management</h1>
          <div class="space-x-2">
            <Button
              @click="loadCategories"
              variant="outline"
              :disabled="loading">
              {{ loading ? "Loading..." : "Refresh" }}
            </Button>
            <Button @click="showForm = true" :disabled="loading">
              Add New Category
            </Button>
          </div>
        </div>

        <!-- Create/Edit Form -->
        <Card v-if="showForm" class="mb-6">
          <CardHeader>
            <CardTitle>
              {{ editingCategory ? "Edit Category" : "Create New Category" }}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <form @submit.prevent="saveCategory" class="space-y-4">
              <!-- Category Name -->
              <div class="space-y-2">
                <Label for="name">Category Name</Label>
                <Input
                  id="name"
                  v-model="formData.name"
                  placeholder="Enter category name"
                  required
                  :disabled="loading" />
              </div>

              <!-- Icon Selection -->
              <div class="space-y-2">
                <Label>Icon</Label>
                <div class="grid grid-cols-10 gap-2">
                  <button
                    v-for="icon in availableIcons"
                    :key="icon"
                    type="button"
                    @click="formData.icon = icon"
                    :class="[
                      'p-2 text-xl border rounded hover:bg-gray-100',
                      formData.icon === icon
                        ? 'border-blue-500 bg-blue-50'
                        : 'border-gray-300',
                    ]"
                    :disabled="loading">
                    {{ icon }}
                  </button>
                </div>
                <Input
                  v-model="formData.icon"
                  placeholder="Or enter custom emoji"
                  class="mt-2" />
              </div>

              <!-- Color Selection -->
              <div class="space-y-2">
                <Label>Color</Label>
                <div class="grid grid-cols-10 gap-2">
                  <button
                    v-for="color in availableColors"
                    :key="color"
                    type="button"
                    @click="formData.color = color"
                    :class="[
                      'w-8 h-8 rounded border-2',
                      formData.color === color
                        ? 'border-gray-800'
                        : 'border-gray-300',
                    ]"
                    :style="{ backgroundColor: color }"
                    :disabled="loading"></button>
                </div>
                <Input
                  v-model="formData.color"
                  type="color"
                  class="mt-2 w-full h-10" />
              </div>

              <!-- Form Actions -->
              <div class="flex justify-end space-x-2 pt-4">
                <Button
                  type="button"
                  variant="outline"
                  @click="resetForm"
                  :disabled="loading">
                  Cancel
                </Button>
                <Button type="submit" :disabled="loading">
                  {{
                    loading
                      ? "Saving..."
                      : editingCategory
                        ? "Update"
                        : "Create"
                  }}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>

        <!-- Categories List -->
        <Card>
          <CardHeader>
            <CardTitle>All Categories</CardTitle>
          </CardHeader>
          <CardContent>
            <div
              v-if="loading && allCategories.length === 0"
              class="text-center py-8">
              <p class="text-gray-500">Loading categories...</p>
            </div>

            <div
              v-else-if="allCategories.length === 0"
              class="text-center py-8">
              <p class="text-gray-500">No categories found.</p>
            </div>

            <div v-else class="overflow-x-auto">
              <table class="w-full">
                <thead>
                  <tr class="border-b">
                    <th class="text-left py-2">Icon</th>
                    <th class="text-left py-2">Name</th>
                    <th class="text-left py-2">Color</th>
                    <th class="text-left py-2">Owner</th>
                    <th class="text-left py-2">Created</th>
                    <th class="text-left py-2">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  <tr
                    v-for="category in allCategories"
                    :key="category._id"
                    class="border-b hover:bg-gray-50">
                    <td class="py-3">
                      <span class="text-2xl">{{ category.icon || "📦" }}</span>
                    </td>
                    <td class="py-3 font-medium">{{ category.name }}</td>
                    <td class="py-3">
                      <div class="flex items-center space-x-2">
                        <div
                          class="w-6 h-6 rounded border"
                          :style="{
                            backgroundColor: category.color || '#3B82F6',
                          }"></div>
                        <span class="text-sm text-gray-600">{{
                          category.color || "#3B82F6"
                        }}</span>
                      </div>
                    </td>
                    <td class="py-3">
                      <span
                        v-if="category.userId"
                        class="text-sm bg-blue-100 text-blue-800 px-2 py-1 rounded">
                        User
                      </span>
                      <span
                        v-else
                        class="text-sm bg-green-100 text-green-800 px-2 py-1 rounded">
                        Global
                      </span>
                    </td>
                    <td class="py-3 text-sm text-gray-600">
                      {{ new Date(category.createdAt).toLocaleDateString() }}
                    </td>
                    <td class="py-3">
                      <div class="flex space-x-2">
                        <Button
                          size="sm"
                          variant="outline"
                          @click="editCategory(category)"
                          :disabled="loading">
                          Edit
                        </Button>
                        <Button
                          size="sm"
                          variant="destructive"
                          @click="deleteCategory(category._id)"
                          :disabled="loading">
                          Delete
                        </Button>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  </PageLayout>
</template>
