<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 { Checkbox } from "@/Components/ui/checkbox";
import { Badge } from "@/Components/ui/badge";
import { Textarea } from "@/Components/ui/textarea";
import { useForm, router } from "@inertiajs/vue3";
import { ref } from "vue";
import { Plus, Pencil, Trash } from "lucide-vue-next";

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

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

const createForm = useForm({
  column: "",
  operator: "=",
  value_type: "static",
  value: "",
  filter_key: "",
  logical_operator: "AND",
  group_id: 1,
  order: 0,
  enabled: true,
});

const editForm = useForm({
  column: "",
  operator: "=",
  value_type: "static",
  value: "",
  filter_key: "",
  logical_operator: "AND",
  group_id: 1,
  order: 0,
  enabled: true,
});

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

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

function openEditDialog(condition) {
  editingCondition.value = condition;
  editForm.column = condition.column;
  editForm.operator = condition.operator;
  editForm.value_type = condition.value_type;
  editForm.value = condition.value || "";
  editForm.filter_key = condition.filter_key || "";
  editForm.logical_operator = condition.logical_operator;
  editForm.group_id = condition.group_id;
  editForm.order = condition.order;
  editForm.enabled = condition.enabled;
  showEditDialog.value = true;
}

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

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

<template>
  <Card>
    <CardHeader>
      <div class="flex items-start justify-between">
        <div>
          <CardTitle>WHERE Conditions</CardTitle>
          <CardDescription>
            Define WHERE clause rules for filtering data
          </CardDescription>
        </div>
        <Button @click="openCreateDialog">
          <Plus class="mr-2 h-4 w-4" />
          Add Condition
        </Button>
      </div>
    </CardHeader>
    <CardContent>
      <div v-if="conditions.length === 0" class="text-center py-8 text-gray-500">
        No conditions configured. Add WHERE conditions to filter query results.
      </div>

      <div v-else class="space-y-3">
        <div
          v-for="condition in conditions"
          :key="condition.id"
          class="flex items-start justify-between rounded-lg border p-4"
          :class="{ 'opacity-50': !condition.enabled }"
        >
          <div class="flex-1">
            <div class="flex items-center gap-2 mb-2">
              <Badge :variant="condition.logical_operator === 'AND' ? 'default' : 'secondary'">
                {{ condition.logical_operator }}
              </Badge>
              <Badge variant="outline">Group {{ condition.group_id || 0 }}</Badge>
              <Badge v-if="!condition.enabled" variant="secondary">disabled</Badge>
            </div>
            <div class="text-sm font-mono mb-1">
              {{ condition.column }} {{ condition.operator }}
              <span v-if="condition.value_type === 'static'" class="text-blue-600">"{{ condition.value }}"</span>
              <span v-else-if="condition.value_type === 'filter'" class="text-green-600">filter({{ condition.filter_key }})</span>
              <span v-else class="text-purple-600">{{ condition.value }}</span>
            </div>
            <div class="text-xs text-gray-500">
              Type: {{ condition.value_type }} | Order: {{ condition.order }}
            </div>
          </div>
          <div class="flex gap-2">
            <Button variant="ghost" size="icon" @click="openEditDialog(condition)">
              <Pencil class="h-4 w-4" />
            </Button>
            <Button variant="ghost" size="icon" @click="deleteCondition(condition)">
              <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 Condition</DialogTitle>
        <DialogDescription>
          Add a new WHERE clause condition
        </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-operator">Operator *</Label>
          <Select v-model="createForm.operator">
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="=">=</SelectItem>
              <SelectItem value="!=">!=</SelectItem>
              <SelectItem value=">">></SelectItem>
              <SelectItem value="<"><</SelectItem>
              <SelectItem value=">=">>=</SelectItem>
              <SelectItem value="<="><=</SelectItem>
              <SelectItem value="LIKE">LIKE</SelectItem>
              <SelectItem value="IN">IN</SelectItem>
              <SelectItem value="NOT IN">NOT IN</SelectItem>
              <SelectItem value="BETWEEN">BETWEEN</SelectItem>
              <SelectItem value="IS NULL">IS NULL</SelectItem>
              <SelectItem value="IS NOT NULL">IS NOT NULL</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div class="space-y-2">
          <Label for="create-value-type">Value Type *</Label>
          <Select v-model="createForm.value_type">
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="static">static (hardcoded value)</SelectItem>
              <SelectItem value="filter">filter (from user input)</SelectItem>
              <SelectItem value="expression">expression (SQL expression)</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div v-if="createForm.value_type === 'filter'" class="space-y-2">
          <Label for="create-filter-key">Filter Key *</Label>
          <Input
            id="create-filter-key"
            v-model="createForm.filter_key"
            placeholder="client_uuid"
          />
        </div>

        <div v-else class="space-y-2">
          <Label for="create-value">Value</Label>
          <Textarea
            id="create-value"
            v-model="createForm.value"
            placeholder="Value or expression..."
            rows="2"
          />
        </div>

        <div class="grid grid-cols-2 gap-4">
          <div class="space-y-2">
            <Label for="create-logical">Logical Operator *</Label>
            <Select v-model="createForm.logical_operator">
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="AND">AND</SelectItem>
                <SelectItem value="OR">OR</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div class="space-y-2">
            <Label for="create-group">Group ID</Label>
            <Input
              id="create-group"
              v-model.number="createForm.group_id"
              type="number"
              placeholder="1"
            />
          </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>

        <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">
            Add Condition
          </Button>
        </DialogFooter>
      </form>
    </DialogContent>
  </Dialog>

  <!-- Edit Dialog -->
  <Dialog v-model:open="showEditDialog">
    <DialogContent class="max-w-2xl">
      <DialogHeader>
        <DialogTitle>Edit Condition</DialogTitle>
        <DialogDescription>
          Update condition 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-operator">Operator *</Label>
          <Select v-model="editForm.operator">
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="=">=</SelectItem>
              <SelectItem value="!=">!=</SelectItem>
              <SelectItem value=">">></SelectItem>
              <SelectItem value="<"><</SelectItem>
              <SelectItem value=">=">>=</SelectItem>
              <SelectItem value="<="><=</SelectItem>
              <SelectItem value="LIKE">LIKE</SelectItem>
              <SelectItem value="IN">IN</SelectItem>
              <SelectItem value="NOT IN">NOT IN</SelectItem>
              <SelectItem value="BETWEEN">BETWEEN</SelectItem>
              <SelectItem value="IS NULL">IS NULL</SelectItem>
              <SelectItem value="IS NOT NULL">IS NOT NULL</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div class="space-y-2">
          <Label for="edit-value-type">Value Type *</Label>
          <Select v-model="editForm.value_type">
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="static">static (hardcoded value)</SelectItem>
              <SelectItem value="filter">filter (from user input)</SelectItem>
              <SelectItem value="expression">expression (SQL expression)</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div v-if="editForm.value_type === 'filter'" class="space-y-2">
          <Label for="edit-filter-key">Filter Key *</Label>
          <Input
            id="edit-filter-key"
            v-model="editForm.filter_key"
          />
        </div>

        <div v-else class="space-y-2">
          <Label for="edit-value">Value</Label>
          <Textarea
            id="edit-value"
            v-model="editForm.value"
            rows="2"
          />
        </div>

        <div class="grid grid-cols-2 gap-4">
          <div class="space-y-2">
            <Label for="edit-logical">Logical Operator *</Label>
            <Select v-model="editForm.logical_operator">
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="AND">AND</SelectItem>
                <SelectItem value="OR">OR</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div class="space-y-2">
            <Label for="edit-group">Group ID</Label>
            <Input
              id="edit-group"
              v-model.number="editForm.group_id"
              type="number"
            />
          </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>

        <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 Condition
          </Button>
        </DialogFooter>
      </form>
    </DialogContent>
  </Dialog>
</template>
