<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 } from "lucide-vue-next";

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

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

const createForm = useForm({
  model_class: "",
  alias: "",
  join_type: "base",
  join_first: "",
  join_operator: "=",
  join_second: "",
  order: 0,
});

const editForm = useForm({
  model_class: "",
  alias: "",
  join_type: "base",
  join_first: "",
  join_operator: "=",
  join_second: "",
  order: 0,
});

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

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

function openEditDialog(entity) {
  editingEntity.value = entity;
  editForm.model_class = entity.model_class;
  editForm.alias = entity.alias || "";
  editForm.join_type = entity.join_type;
  editForm.join_first = entity.join_first || "";
  editForm.join_operator = entity.join_operator || "=";
  editForm.join_second = entity.join_second || "";
  editForm.order = entity.order;
  showEditDialog.value = true;
}

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

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

<template>
  <Card>
    <CardHeader>
      <div class="flex items-start justify-between">
        <div>
          <CardTitle>Database Entities & Joins</CardTitle>
          <CardDescription>
            Configure which models/tables to query and how to join them
          </CardDescription>
        </div>
        <Button @click="openCreateDialog">
          <Plus class="mr-2 h-4 w-4" />
          Add Entity
        </Button>
      </div>
    </CardHeader>
    <CardContent>
      <div v-if="entities.length === 0" class="text-center py-8 text-gray-500">
        No entities configured. Add a base entity to get started.
      </div>

      <div v-else class="space-y-3">
        <div
          v-for="entity in entities"
          :key="entity.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">
              <Badge :variant="entity.join_type === 'base' ? 'default' : 'secondary'">
                {{ entity.join_type }}
              </Badge>
              <span class="font-mono text-sm">{{ entity.model_class }}</span>
              <Badge v-if="entity.alias" variant="outline">as {{ entity.alias }}</Badge>
            </div>
            <div v-if="entity.join_type !== 'base'" class="text-sm text-gray-600 dark:text-gray-400">
              {{ entity.join_first }} {{ entity.join_operator }} {{ entity.join_second }}
            </div>
            <div class="text-xs text-gray-500 mt-1">Order: {{ entity.order }}</div>
          </div>
          <div class="flex gap-2">
            <Button variant="ghost" size="icon" @click="openEditDialog(entity)">
              <Pencil class="h-4 w-4" />
            </Button>
            <Button variant="ghost" size="icon" @click="deleteEntity(entity)">
              <Trash class="h-4 w-4 text-destructive" />
            </Button>
          </div>
        </div>
      </div>
    </CardContent>
  </Card>

  <!-- Create Dialog -->
  <Dialog v-model:open="showCreateDialog">
    <DialogContent class="max-w-2xl">
      <DialogHeader>
        <DialogTitle>Add Entity</DialogTitle>
        <DialogDescription>
          Add a model/table to the report query
        </DialogDescription>
      </DialogHeader>

      <form @submit.prevent="submitCreate" class="space-y-4">
        <div class="space-y-2">
          <Label for="create-model">Model Class *</Label>
          <Input
            id="create-model"
            v-model="createForm.model_class"
            placeholder="App\Models\Contract"
            required
          />
        </div>

        <div class="space-y-2">
          <Label for="create-alias">Alias (optional)</Label>
          <Input
            id="create-alias"
            v-model="createForm.alias"
            placeholder="contracts"
          />
        </div>

        <div class="space-y-2">
          <Label for="create-join-type">Join Type *</Label>
          <Select v-model="createForm.join_type">
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="base">base (no join)</SelectItem>
              <SelectItem value="join">join (INNER JOIN)</SelectItem>
              <SelectItem value="leftJoin">leftJoin (LEFT JOIN)</SelectItem>
              <SelectItem value="rightJoin">rightJoin (RIGHT JOIN)</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div v-if="createForm.join_type !== 'base'" class="grid grid-cols-3 gap-4">
          <div class="space-y-2">
            <Label for="create-join-first">Join First Column *</Label>
            <Input
              id="create-join-first"
              v-model="createForm.join_first"
              placeholder="contracts.client_id"
            />
          </div>

          <div class="space-y-2">
            <Label for="create-join-op">Operator *</Label>
            <Select v-model="createForm.join_operator">
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="=">=</SelectItem>
                <SelectItem value="!=">!=</SelectItem>
                <SelectItem value=">">></SelectItem>
                <SelectItem value="<"><</SelectItem>
                <SelectItem value=">=">>=</SelectItem>
                <SelectItem value="<="><=</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div class="space-y-2">
            <Label for="create-join-second">Join Second Column *</Label>
            <Input
              id="create-join-second"
              v-model="createForm.join_second"
              placeholder="clients.id"
            />
          </div>
        </div>

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

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

  <!-- Edit Dialog -->
  <Dialog v-model:open="showEditDialog">
    <DialogContent class="max-w-2xl">
      <DialogHeader>
        <DialogTitle>Edit Entity</DialogTitle>
        <DialogDescription>
          Update entity configuration
        </DialogDescription>
      </DialogHeader>

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

        <div class="space-y-2">
          <Label for="edit-alias">Alias (optional)</Label>
          <Input
            id="edit-alias"
            v-model="editForm.alias"
          />
        </div>

        <div class="space-y-2">
          <Label for="edit-join-type">Join Type *</Label>
          <Select v-model="editForm.join_type">
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="base">base (no join)</SelectItem>
              <SelectItem value="join">join (INNER JOIN)</SelectItem>
              <SelectItem value="leftJoin">leftJoin (LEFT JOIN)</SelectItem>
              <SelectItem value="rightJoin">rightJoin (RIGHT JOIN)</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div v-if="editForm.join_type !== 'base'" class="grid grid-cols-3 gap-4">
          <div class="space-y-2">
            <Label for="edit-join-first">Join First Column *</Label>
            <Input
              id="edit-join-first"
              v-model="editForm.join_first"
            />
          </div>

          <div class="space-y-2">
            <Label for="edit-join-op">Operator *</Label>
            <Select v-model="editForm.join_operator">
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="=">=</SelectItem>
                <SelectItem value="!=">!=</SelectItem>
                <SelectItem value=">">></SelectItem>
                <SelectItem value="<"><</SelectItem>
                <SelectItem value=">=">>=</SelectItem>
                <SelectItem value="<="><=</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div class="space-y-2">
            <Label for="edit-join-second">Join Second Column *</Label>
            <Input
              id="edit-join-second"
              v-model="editForm.join_second"
            />
          </div>
        </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 Entity
          </Button>
        </DialogFooter>
      </form>
    </DialogContent>
  </Dialog>
</template>
