<script setup>
import AppLayout from "@/Layouts/AppLayout.vue";
import AppCard from "@/Components/app/ui/card/AppCard.vue";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/Components/ui/card";
import { Button } from "@/Components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/Components/ui/dialog";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/Components/ui/dropdown-menu";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { Textarea } from "@/Components/ui/textarea";
import { Checkbox } from "@/Components/ui/checkbox";
import { Badge } from "@/Components/ui/badge";
import { useForm, router, Link } from "@inertiajs/vue3";
import { ref } from "vue";
import { BarChart3, MoreHorizontal, Pencil, Trash, Power, PowerOff, Plus, Database } from "lucide-vue-next";

const props = defineProps({
  reports: Array,
});

const showCreateDialog = ref(false);
const showEditDialog = ref(false);
const editingReport = ref(null);

const createForm = useForm({
  slug: "",
  name: "",
  description: "",
  category: "",
  enabled: true,
  order: 0,
});

const editForm = useForm({
  slug: "",
  name: "",
  description: "",
  category: "",
  enabled: true,
  order: 0,
});

function openCreateDialog() {
  createForm.reset();
  showCreateDialog.value = true;
}

function submitCreate() {
  createForm.post(route("settings.reports.store"), {
    preserveScroll: true,
    onSuccess: () => {
      showCreateDialog.value = false;
      createForm.reset();
    },
  });
}

function openEditDialog(report) {
  editingReport.value = report;
  editForm.slug = report.slug;
  editForm.name = report.name;
  editForm.description = report.description || "";
  editForm.category = report.category || "";
  editForm.enabled = report.enabled;
  editForm.order = report.order;
  showEditDialog.value = true;
}

function submitEdit() {
  editForm.put(route("settings.reports.update", editingReport.value.id), {
    preserveScroll: true,
    onSuccess: () => {
      showEditDialog.value = false;
      editForm.reset();
      editingReport.value = null;
    },
  });
}

function toggleEnabled(report) {
  router.post(
    route("settings.reports.toggle", report.id),
    {},
    {
      preserveScroll: true,
    }
  );
}

function deleteReport(report) {
  if (confirm(`Are you sure you want to delete "${report.name}"?`)) {
    router.delete(route("settings.reports.destroy", report.id), {
      preserveScroll: true,
    });
  }
}
</script>

<template>
  <AppLayout title="Reports Settings">
    <template #header>
      <h2 class="text-xl font-semibold leading-tight text-gray-800 dark:text-gray-200">
        Reports Settings
      </h2>
    </template>

    <div class="py-12">
      <div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
        <AppCard>
          <template #icon>
            <div class="flex h-12 w-12 items-center justify-center rounded-lg bg-primary/10">
              <BarChart3 class="h-6 w-6 text-primary" />
            </div>
          </template>

          <template #header>
            <CardTitle>Database Reports</CardTitle>
            <CardDescription>
              Manage configurable reports with dynamic queries and filters
            </CardDescription>
          </template>

          <template #headerActions>
            <Button @click="openCreateDialog">
              <Plus class="mr-2 h-4 w-4" />
              Create Report
            </Button>
          </template>

          <div class="space-y-4">
            <div v-if="reports.length === 0" class="text-center py-8 text-gray-500">
              No reports configured yet. Create your first report to get started.
            </div>

            <Card v-for="report in reports" :key="report.id" class="overflow-hidden">
              <CardHeader class="bg-gray-50 dark:bg-gray-800/50">
                <div class="flex items-start justify-between">
                  <div class="flex-1">
                    <div class="flex items-center gap-2">
                      <CardTitle class="text-base">{{ report.name }}</CardTitle>
                      <Badge v-if="!report.enabled" variant="secondary">Disabled</Badge>
                      <Badge v-if="report.category" variant="outline">{{ report.category }}</Badge>
                    </div>
                    <CardDescription class="mt-1">
                      {{ report.description || "No description" }}
                    </CardDescription>
                  </div>

                  <DropdownMenu>
                    <DropdownMenuTrigger as-child>
                      <Button variant="ghost" size="icon">
                        <MoreHorizontal class="h-4 w-4" />
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                      <DropdownMenuItem @click="openEditDialog(report)">
                        <Pencil class="mr-2 h-4 w-4" />
                        Edit
                      </DropdownMenuItem>
                      <DropdownMenuItem as-child>
                        <Link :href="route('settings.reports.edit', report.id)" class="flex items-center cursor-pointer">
                          <Database class="mr-2 h-4 w-4" />
                          Configure Details
                        </Link>
                      </DropdownMenuItem>
                      <DropdownMenuSeparator />
                      <DropdownMenuItem @click="toggleEnabled(report)">
                        <Power v-if="report.enabled" class="mr-2 h-4 w-4" />
                        <PowerOff v-else class="mr-2 h-4 w-4" />
                        {{ report.enabled ? "Disable" : "Enable" }}
                      </DropdownMenuItem>
                      <DropdownMenuItem @click="deleteReport(report)" class="text-destructive">
                        <Trash class="mr-2 h-4 w-4" />
                        Delete
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </div>
              </CardHeader>

              <CardContent class="pt-4">
                <div class="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <span class="text-gray-500 dark:text-gray-400">Slug:</span>
                    <span class="ml-2 font-mono text-xs">{{ report.slug }}</span>
                  </div>
                  <div>
                    <span class="text-gray-500 dark:text-gray-400">Order:</span>
                    <span class="ml-2">{{ report.order }}</span>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </AppCard>

        <!-- Create Dialog -->
        <Dialog v-model:open="showCreateDialog">
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Create New Report</DialogTitle>
              <DialogDescription>
                Create a new database-driven report configuration
              </DialogDescription>
            </DialogHeader>

            <form @submit.prevent="submitCreate" class="space-y-4">
              <div class="space-y-2">
                <Label for="create-slug">Slug *</Label>
                <Input
                  id="create-slug"
                  v-model="createForm.slug"
                  placeholder="active-contracts"
                  required
                />
                <p class="text-xs text-gray-500">Unique identifier for the report</p>
              </div>

              <div class="space-y-2">
                <Label for="create-name">Name *</Label>
                <Input
                  id="create-name"
                  v-model="createForm.name"
                  placeholder="Active Contracts"
                  required
                />
              </div>

              <div class="space-y-2">
                <Label for="create-description">Description</Label>
                <Textarea
                  id="create-description"
                  v-model="createForm.description"
                  placeholder="Report description..."
                  rows="3"
                />
              </div>

              <div class="space-y-2">
                <Label for="create-category">Category</Label>
                <Input
                  id="create-category"
                  v-model="createForm.category"
                  placeholder="contracts, activities, financial..."
                />
              </div>

              <div class="space-y-2">
                <Label for="create-order">Display Order</Label>
                <Input
                  id="create-order"
                  v-model.number="createForm.order"
                  type="number"
                  placeholder="0"
                />
              </div>

              <div class="flex items-center space-x-2">
                <Checkbox
                  id="create-enabled"
                  v-model="createForm.enabled"
                />
                <Label for="create-enabled" class="cursor-pointer">
                  Enabled
                </Label>
              </div>

              <DialogFooter>
                <Button type="button" variant="outline" @click="showCreateDialog = false">
                  Cancel
                </Button>
                <Button type="submit" :disabled="createForm.processing">
                  Create Report
                </Button>
              </DialogFooter>
            </form>
          </DialogContent>
        </Dialog>

        <!-- Edit Dialog -->
        <Dialog v-model:open="showEditDialog">
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Edit Report</DialogTitle>
              <DialogDescription>
                Update report configuration
              </DialogDescription>
            </DialogHeader>

            <form @submit.prevent="submitEdit" class="space-y-4">
              <div class="space-y-2">
                <Label for="edit-slug">Slug *</Label>
                <Input
                  id="edit-slug"
                  v-model="editForm.slug"
                  required
                />
              </div>

              <div class="space-y-2">
                <Label for="edit-name">Name *</Label>
                <Input
                  id="edit-name"
                  v-model="editForm.name"
                  required
                />
              </div>

              <div class="space-y-2">
                <Label for="edit-description">Description</Label>
                <Textarea
                  id="edit-description"
                  v-model="editForm.description"
                  rows="3"
                />
              </div>

              <div class="space-y-2">
                <Label for="edit-category">Category</Label>
                <Input
                  id="edit-category"
                  v-model="editForm.category"
                />
              </div>

              <div class="space-y-2">
                <Label for="edit-order">Display Order</Label>
                <Input
                  id="edit-order"
                  v-model.number="editForm.order"
                  type="number"
                />
              </div>

              <div class="flex items-center space-x-2">
                <Checkbox
                  id="edit-enabled"
                  v-model="editForm.enabled"
                />
                <Label for="edit-enabled" class="cursor-pointer">
                  Enabled
                </Label>
              </div>

              <DialogFooter>
                <Button type="button" variant="outline" @click="showEditDialog = false">
                  Cancel
                </Button>
                <Button type="submit" :disabled="editForm.processing">
                  Update Report
                </Button>
              </DialogFooter>
            </form>
          </DialogContent>
        </Dialog>
      </div>
    </div>
  </AppLayout>
</template>
