<script setup>
import { Button } from "@/Components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/Components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/Components/ui/select";
import { Checkbox } from "@/Components/ui/checkbox";
import AppCheckboxArray from "@/Components/app/ui/AppCheckboxArray.vue";
import { Input } from "@/Components/ui/input";
import { Textarea } from "@/Components/ui/textarea";
import { Alert, AlertDescription } from "@/Components/ui/alert";
import InputLabel from "@/Components/InputLabel.vue";
import InputError from "@/Components/InputError.vue";
import { ref, computed, watch } from "vue";

const props = defineProps({
  form: Object,
  setting: Object,
  archiveEntities: Array,
  actions: Array,
  segments: Array,
});

const emit = defineEmits(["submit", "cancel"]);

const selectedEntity = ref(null);

// Initialize selectedEntity based on form.focus
watch(
  () => props.form.focus,
  (newFocus) => {
    const found = props.archiveEntities.find((e) => e.focus === newFocus);
    selectedEntity.value = found || null;
  },
  { immediate: true }
);

const availableDecisions = computed(() => {
  if (!props.form.action_id) return [];
  const action = props.actions.find((a) => a.id === props.form.action_id);
  return action?.decisions || [];
});

function handleActionChange() {
  props.form.decision_id = null;
}
</script>

<template>
  <Card>
    <CardHeader>
      <CardTitle class="text-base">Edit Rule #{{ setting.id }}</CardTitle>
    </CardHeader>
    <CardContent class="space-y-4">
      <Alert v-if="setting.strategy === 'manual'" variant="default">
        <AlertDescription class="text-xs">
          Manual strategy: this rule will only run when triggered manually.
        </AlertDescription>
      </Alert>

      <div>
        <InputLabel for="edit_segment">Segment (optional)</InputLabel>
        <Select v-model="form.segment_id">
          <SelectTrigger id="edit_segment" class="w-full">
            <SelectValue placeholder="-- none --" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem :value="null">-- none --</SelectItem>
            <SelectItem v-for="seg in segments" :key="seg.id" :value="seg.id">
              {{ seg.name }}
            </SelectItem>
          </SelectContent>
        </Select>
      </div>

      <div>
        <InputLabel for="edit_action">Action (optional)</InputLabel>
        <Select v-model="form.action_id" @update:model-value="handleActionChange">
          <SelectTrigger id="edit_action" class="w-full">
            <SelectValue placeholder="-- none --" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem :value="null">-- none --</SelectItem>
            <SelectItem v-for="a in actions" :key="a.id" :value="a.id">
              {{ a.name }}
            </SelectItem>
          </SelectContent>
        </Select>
      </div>

      <div>
        <InputLabel for="edit_decision">Decision (optional)</InputLabel>
        <Select v-model="form.decision_id" :disabled="!form.action_id">
          <SelectTrigger id="edit_decision" class="w-full">
            <SelectValue placeholder="-- none --" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem :value="null">-- none --</SelectItem>
            <SelectItem v-for="d in availableDecisions" :key="d.id" :value="d.id">
              {{ d.name }}
            </SelectItem>
          </SelectContent>
        </Select>
      </div>

      <div>
        <InputLabel for="edit_name">Name</InputLabel>
        <Input id="edit_name" v-model="form.name" type="text" />
        <InputError :message="form.errors.name" class="mt-1" />
      </div>

      <div>
        <InputLabel for="edit_focus">Focus Entity</InputLabel>
        <Select v-model="form.focus">
          <SelectTrigger id="edit_focus" class="w-full">
            <SelectValue placeholder="-- choose --" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem v-for="ae in archiveEntities" :key="ae.id" :value="ae.focus">
              {{ ae.name || ae.focus }}
            </SelectItem>
          </SelectContent>
        </Select>
      </div>

      <div v-if="selectedEntity && form.focus === selectedEntity.focus" class="space-y-2">
        <InputLabel>Related Tables</InputLabel>
        <div class="flex flex-wrap gap-2">
          <label
            v-for="r in selectedEntity.related"
            :key="r"
            class="inline-flex items-center gap-2 text-sm bg-muted px-3 py-1.5 rounded-md border cursor-pointer hover:bg-muted/80"
          >
            <AppCheckboxArray :value="r" v-model="form.related" />
            <span>{{ r }}</span>
          </label>
        </div>
      </div>

      <div>
        <InputLabel for="edit_description">Description</InputLabel>
        <Textarea id="edit_description" v-model="form.description" rows="2" />
        <InputError :message="form.errors.description" class="mt-1" />
      </div>

      <div class="flex items-center gap-2">
        <Checkbox id="edit_enabled" v-model="form.enabled" />
        <InputLabel for="edit_enabled" class="text-sm font-normal cursor-pointer">
          Enabled
        </InputLabel>
      </div>

      <div class="flex items-center gap-2">
        <Checkbox id="edit_soft" v-model="form.soft" />
        <InputLabel for="edit_soft" class="text-sm font-normal cursor-pointer">
          Soft Archive
        </InputLabel>
      </div>

      <div class="flex items-center gap-2">
        <Checkbox id="edit_reactivate" v-model="form.reactivate" />
        <InputLabel for="edit_reactivate" class="text-sm font-normal cursor-pointer">
          Reactivate (undo archive)
        </InputLabel>
      </div>

      <div>
        <InputLabel for="edit_strategy">Strategy</InputLabel>
        <Select v-model="form.strategy">
          <SelectTrigger id="edit_strategy" class="w-full">
            <SelectValue placeholder="Select strategy" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="immediate">Immediate</SelectItem>
            <SelectItem value="scheduled">Scheduled</SelectItem>
            <SelectItem value="queued">Queued</SelectItem>
            <SelectItem value="manual">Manual (never auto-run)</SelectItem>
          </SelectContent>
        </Select>
        <InputError :message="form.errors.strategy" class="mt-1" />
      </div>

      <div class="flex gap-2">
        <Button @click="emit('submit')" :disabled="form.processing" class="flex-1">
          Update
        </Button>
        <Button @click="emit('cancel')" variant="outline"> Cancel </Button>
      </div>

      <div v-if="Object.keys(form.errors).length" class="text-xs text-red-600">
        Please fix validation errors.
      </div>
    </CardContent>
  </Card>
</template>
