<script setup>
import AppLayout from "@/Layouts/AppLayout.vue";
import { ref, computed, watch } from "vue";
import { useForm } from "@inertiajs/vue3";
import AppMultiSelect from "@/Components/app/ui/AppMultiSelect.vue";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/Components/ui/card";
import { Label } from "@/Components/ui/label";
import { Input } from "@/Components/ui/input";
import { Textarea } from "@/Components/ui/textarea";
import { Button } from "@/Components/ui/button";
import { Checkbox } from "@/Components/ui/checkbox";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/Components/ui/select";
import { Badge } from "@/Components/ui/badge";
import { Separator } from "@/Components/ui/separator";

const props = defineProps({
  clients: Array,
  segments: Array,
  decisions: Array,
  actions: Array,
});

const form = useForm({
  name: "",
  description: "",
  source_type: "csv",
  default_record_type: "",
  is_active: true,
  reactivate: false,
  client_uuid: null,
  entities: [],
  meta: {
    segment_id: null,
    decision_id: null,
    action_id: null,
    delimiter: "",
    // Payments import mode
    payments_import: false,
    // History import mode
    history_import: false,
    // For payments mode: how to locate Contract - use single key 'reference'
    contract_key_mode: null,
  },
});

const decisionsForSelectedAction = computed(() => {
  const act = (props.actions || []).find((a) => a.id === form.meta.action_id);
  return act?.decisions || [];
});

watch(
  () => form.meta.action_id,
  () => {
    // Clear decision when action changes to enforce valid pair
    form.meta.decision_id = null;
  }
);

function submit() {
  form.post(route("importTemplates.store"), {
    onSuccess: () => {
      // You can redirect or show a success message here
    },
  });
}

// Payments mode: lock entities to Contract -> Account -> Payment and provide key mode
const prevEntities = ref([]);
watch(
  () => form.meta.payments_import,
  (enabled) => {
    if (enabled && form.meta.history_import) {
      form.meta.history_import = false;
    }
    if (enabled) {
      // Save current selection and lock to the required chain
      prevEntities.value = Array.isArray(form.entities) ? [...form.entities] : [];
      form.entities = ["contracts", "accounts", "payments"];
      // default contract key mode to 'reference'
      if (!form.meta.contract_key_mode) {
        form.meta.contract_key_mode = "reference";
      }
    } else {
      // Restore previous selection when turning off
      form.entities = prevEntities.value?.length ? [...prevEntities.value] : [];
      form.meta.contract_key_mode = null;
    }
  }
);

// History import: restrict entities and auto-add accounts when contracts selected
watch(
  () => form.meta.history_import,
  (enabled) => {
    if (enabled && form.meta.payments_import) {
      form.meta.payments_import = false;
      form.meta.contract_key_mode = null;
    }
    const allowed = [
      "person",
      "person_addresses",
      "person_phones",
      "contracts",
      "activities",
      "client_cases",
    ];
    if (enabled) {
      const current = Array.isArray(form.entities) ? [...form.entities] : [];
      let filtered = current.filter((e) => allowed.includes(e));
      if (filtered.includes("contracts") && !filtered.includes("accounts")) {
        filtered = [...filtered, "accounts"];
      }
      form.entities = filtered;
    }
  }
);

watch(
  () => form.entities,
  (vals) => {
    if (
      form.meta.history_import &&
      Array.isArray(vals) &&
      vals.includes("contracts") &&
      !vals.includes("accounts")
    ) {
      form.entities = [...vals, "accounts"];
    }
  }
);
</script>

<template>
  <AppLayout title="Ustvari predlogo uvoza">
    <template #header> </template>

    <div class="py-6">
      <div class="max-w-3xl mx-auto sm:px-6 lg:px-8">
        <Card>
          <CardHeader>
            <CardTitle>Konfiguracija predloge</CardTitle>
            <CardDescription
              >Določite nastavitve predloge uvoza in ciljne entitete</CardDescription
            >
          </CardHeader>
          <CardContent class="space-y-6">
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div class="space-y-2">
                <Label for="client">Stranka (izbirno)</Label>
                <Select v-model="form.client_uuid">
                  <SelectTrigger id="client">
                    <SelectValue placeholder="Globalno (brez stranke)" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem :value="null">Globalno (brez stranke)</SelectItem>
                    <SelectItem
                      v-for="c in props.clients || []"
                      :key="c.uuid"
                      :value="c.uuid"
                    >
                      {{ c.name }}
                    </SelectItem>
                  </SelectContent>
                </Select>
                <p class="text-xs text-muted-foreground">
                  Pustite prazno za globalno predlogo (vidno vsem strankam).
                </p>
              </div>
              <div class="space-y-2">
                <Label>Entitete (tabele)</Label>
                <template v-if="!form.meta.payments_import">
                  <AppMultiSelect
                    v-model="form.entities"
                    :items="[
                      { value: 'person', label: 'Oseba' },
                      { value: 'person_addresses', label: 'Naslov' },
                      { value: 'person_phones', label: 'Telefon' },
                      { value: 'client_cases', label: 'Primer' },
                      { value: 'emails', label: 'E-pošta' },
                      { value: 'accounts', label: 'Računi' },
                      { value: 'contracts', label: 'Pogodbe' },
                      { value: 'case_objects', label: 'Predmet' },
                      { value: 'payments', label: 'Plačilo' },
                      { value: 'activities', label: 'Aktivnost' },
                    ]"
                    placeholder="Izberite eno ali več entitet"
                    search-placeholder="Iskanje entitet..."
                    content-class="p-0 w-full"
                  />
                </template>
                <template v-else>
                  <div class="flex flex-wrap gap-2">
                    <Badge variant="secondary">Pogodbe</Badge>
                    <Badge variant="secondary">Računi</Badge>
                    <Badge variant="secondary">Plačila</Badge>
                  </div>
                </template>
                <p class="text-xs text-muted-foreground mt-1">
                  Izberite katere tabele ta predloga cilja. Preslikave stolpcev lahko
                  dodate kasneje.
                </p>

                <!-- Import Mode Toggles -->
                <div class="flex items-center gap-6 pt-2">
                  <label class="inline-flex items-center gap-2">
                    <Checkbox
                      :checked="form.meta.history_import"
                      @update:checked="form.meta.history_import = $event"
                    />
                    <span class="text-sm">Uvoz zgodovine</span>
                  </label>
                  <label class="inline-flex items-center gap-2">
                    <Checkbox
                      :checked="form.meta.payments_import"
                      @update:checked="form.meta.payments_import = $event"
                    />
                    <span class="text-sm">Uvoz plačil</span>
                  </label>
                </div>

                <div
                  v-if="form.meta.history_import"
                  class="mt-2 text-xs text-muted-foreground"
                >
                  Način zgodovine dovoljuje samo
                  oseba/naslovi/telefoni/pogodbe/aktivnosti/primeri strank. Računi so
                  samodejno dodani, ko so prisotne pogodbe in stanja ostanejo
                  nespremenjena.
                </div>
                <div
                  v-if="form.meta.payments_import"
                  class="mt-2 text-xs text-muted-foreground"
                >
                  Način plačil zaklene entitete na:
                  <span class="font-medium">Pogodbe → Računi → Plačila</span> in
                  optimizira ujemanje za uvoz plačil.
                </div>
                <div v-if="form.meta.payments_import" class="mt-3 space-y-2">
                  <Label>Ključ ujemanja pogodb</Label>
                  <Select v-model="form.meta.contract_key_mode">
                    <SelectTrigger>
                      <SelectValue placeholder="Izberite ključ pogodbe" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="reference">
                        Referenca (uporabi samo contract.reference za iskanje zapisov)
                      </SelectItem>
                    </SelectContent>
                  </Select>
                  <p class="text-xs text-muted-foreground">
                    Pri uvozu plačil se zapisi pogodb najdejo z uporabo izbranega ključa.
                    Uporabite CSV preslikavo za povezavo ustreznega stolpca z referenco
                    pogodbe.
                  </p>
                </div>
              </div>
            </div>

            <Separator />

            <!-- Defaults: Segment / Decision / Action -->
            <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
              <div class="space-y-2">
                <Label>Privzeti segment</Label>
                <Select v-model="form.meta.segment_id">
                  <SelectTrigger>
                    <SelectValue placeholder="(brez)" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem :value="null">(brez)</SelectItem>
                    <SelectItem
                      v-for="s in props.segments || []"
                      :key="s.id"
                      :value="s.id"
                    >
                      {{ s.name }}
                    </SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div class="space-y-2">
                <Label>Privzeto dejanje (za aktivnost)</Label>
                <Select v-model="form.meta.action_id">
                  <SelectTrigger>
                    <SelectValue placeholder="(brez)" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem :value="null">(brez)</SelectItem>
                    <SelectItem
                      v-for="a in props.actions || []"
                      :key="a.id"
                      :value="a.id"
                    >
                      {{ a.name }}
                    </SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div class="space-y-2">
                <Label>Privzeta odločitev</Label>
                <Select v-model="form.meta.decision_id" :disabled="!form.meta.action_id">
                  <SelectTrigger>
                    <SelectValue placeholder="(brez)" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem :value="null">(brez)</SelectItem>
                    <SelectItem
                      v-for="d in decisionsForSelectedAction"
                      :key="d.id"
                      :value="d.id"
                    >
                      {{ d.name }}
                    </SelectItem>
                  </SelectContent>
                </Select>
                <p v-if="!form.meta.action_id" class="text-xs text-muted-foreground">
                  Izberite dejanje za ogled njegovih odločitev.
                </p>
              </div>
            </div>

            <Separator />
            <div class="space-y-2">
              <Label for="name">Ime</Label>
              <Input
                id="name"
                v-model="form.name"
                type="text"
                placeholder="Vnesite ime predloge"
              />
            </div>

            <div class="space-y-2">
              <Label for="description">Opis</Label>
              <Textarea
                id="description"
                v-model="form.description"
                placeholder="Vnesite opis predloge"
                rows="3"
              />
            </div>

            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div class="space-y-2">
                <Label for="source-type">Tip vira</Label>
                <Select v-model="form.source_type">
                  <SelectTrigger id="source-type">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="csv">CSV</SelectItem>
                    <SelectItem value="xml">XML</SelectItem>
                    <SelectItem value="xls">XLS</SelectItem>
                    <SelectItem value="xlsx">XLSX</SelectItem>
                    <SelectItem value="json">JSON</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div class="space-y-2">
                <Label for="record-type">Privzeti tip zapisa (izbirno)</Label>
                <Input
                  id="record-type"
                  v-model="form.default_record_type"
                  type="text"
                  placeholder="npr. račun, oseba"
                />
              </div>
            </div>

            <div class="flex items-center gap-6">
              <div class="flex items-center gap-2">
                <Checkbox
                  id="is_active"
                  :checked="form.is_active"
                  @update:checked="form.is_active = $event"
                />
                <Label for="is_active" class="cursor-pointer">Aktivno</Label>
              </div>
              <div class="flex items-center gap-2">
                <Checkbox
                  id="reactivate"
                  :checked="form.reactivate"
                  @update:checked="form.reactivate = $event"
                />
                <Label for="reactivate" class="cursor-pointer">Uvoz reaktivacije</Label>
              </div>
            </div>

            <Separator />

            <div class="flex items-center justify-between pt-2">
              <div
                v-if="form.errors && Object.keys(form.errors).length"
                class="text-sm text-destructive"
              >
                <div v-for="(msg, key) in form.errors" :key="key">{{ msg }}</div>
              </div>
              <Button @click.prevent="submit" :disabled="form.processing" class="ml-auto">
                {{ form.processing ? "Shranjevanje…" : "Ustvari predlogo" }}
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  </AppLayout>
</template>
