<script setup>
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 { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/ui/select";
import { Badge } from "@/Components/ui/badge";
import { useForm, router } from "@inertiajs/vue3";
import { ref } from "vue";
import { Plus, Pencil, Trash, ArrowUp, ArrowDown } from "lucide-vue-next";

const props = defineProps({
  report: Object,
  orders: Array,
});

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

const createForm = useForm({
  column: "",
  direction: "ASC",
  order: 0,
});

const editForm = useForm({
  column: "",
  direction: "ASC",
  order: 0,
});

function openCreateDialog() {
  createForm.reset();
  createForm.order = props.orders.length;
  showCreateDialog.value = true;
}

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

function openEditDialog(order) {
  editingOrder.value = order;
  editForm.column = order.column;
  editForm.direction = order.direction;
  editForm.order = order.order;
  showEditDialog.value = true;
}

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

function deleteOrder(order) {
  if (confirm("Are you sure you want to delete this order clause?")) {
    router.delete(route("settings.reports.orders.destroy", order.id), {
      preserveScroll: true,
    });
  }
}
</script>

<template>
  <Card>
    <CardHeader>
      <div class="flex items-start justify-between">
        <div>
          <CardTitle>ORDER BY Clauses</CardTitle>
          <CardDescription>
            Define how to sort the report results
          </CardDescription>
        </div>
        <Button @click="openCreateDialog">
          <Plus class="mr-2 h-4 w-4" />
          Add Order
        </Button>
      </div>
    </CardHeader>
    <CardContent>
      <div v-if="orders.length === 0" class="text-center py-8 text-gray-500">
        No order clauses configured. Add ORDER BY clauses to sort results.
      </div>

      <div v-else class="space-y-3">
        <div
          v-for="orderClause in orders"
          :key="orderClause.id"
          class="flex items-start justify-between rounded-lg border p-4"
        >
          <div class="flex-1">
            <div class="flex items-center gap-2 mb-2">
              <ArrowUp v-if="orderClause.direction === 'ASC'" class="h-4 w-4 text-blue-600" />
              <ArrowDown v-else class="h-4 w-4 text-orange-600" />
              <span class="font-mono text-sm">{{ orderClause.column }}</span>
              <Badge :variant="orderClause.direction === 'ASC' ? 'default' : 'secondary'">
                {{ orderClause.direction }}
              </Badge>
            </div>
            <div class="text-xs text-gray-500">Order: {{ orderClause.order }}</div>
          </div>
          <div class="flex gap-2">
            <Button variant="ghost" size="icon" @click="openEditDialog(orderClause)">
              <Pencil class="h-4 w-4" />
            </Button>
            <Button variant="ghost" size="icon" @click="deleteOrder(orderClause)">
              <Trash class="h-4 w-4 text-destructive" />
            </Button>
          </div>
        </div>
      </div>
    </CardContent>
  </Card>

  <!-- Create Dialog -->
  <Dialog v-model:open="showCreateDialog">
    <DialogContent>
      <DialogHeader>
        <DialogTitle>Add Order Clause</DialogTitle>
        <DialogDescription>
          Add a new ORDER BY clause
        </DialogDescription>
      </DialogHeader>

      <form @submit.prevent="submitCreate" class="space-y-4">
        <div class="space-y-2">
          <Label for="create-column">Column *</Label>
          <Input
            id="create-column"
            v-model="createForm.column"
            placeholder="contracts.start_date"
            required
          />
        </div>

        <div class="space-y-2">
          <Label for="create-direction">Direction *</Label>
          <Select v-model="createForm.direction">
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="ASC">ASC (Ascending)</SelectItem>
              <SelectItem value="DESC">DESC (Descending)</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div class="space-y-2">
          <Label for="create-order">Order</Label>
          <Input
            id="create-order"
            v-model.number="createForm.order"
            type="number"
          />
          <p class="text-xs text-gray-500">Determines sort priority (lower = higher priority)</p>
        </div>

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

  <!-- Edit Dialog -->
  <Dialog v-model:open="showEditDialog">
    <DialogContent>
      <DialogHeader>
        <DialogTitle>Edit Order Clause</DialogTitle>
        <DialogDescription>
          Update order clause configuration
        </DialogDescription>
      </DialogHeader>

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

        <div class="space-y-2">
          <Label for="edit-direction">Direction *</Label>
          <Select v-model="editForm.direction">
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="ASC">ASC (Ascending)</SelectItem>
              <SelectItem value="DESC">DESC (Descending)</SelectItem>
            </SelectContent>
          </Select>
        </div>

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

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