<script setup>
import ActionMessage from "@/Components/ActionMessage.vue";
import BasicButton from "@/Components/buttons/BasicButton.vue";
import CreateDialog from "@/Components/Dialogs/CreateDialog.vue";
import DatePicker from "@/Components/DatePicker.vue";
import CurrencyInput from "@/Components/CurrencyInput.vue";
import { useForm as useInertiaForm, usePage, router } from "@inertiajs/vue3";
// Note: This form uses Inertia's useForm for API calls but shadcn-vue components for UI
import { Textarea } from "@/Components/ui/textarea";
import { Label } from "@/Components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/Components/ui/select";
import { Switch } from "@/Components/ui/switch";
import AppMultiSelect from "@/Components/app/ui/AppMultiSelect.vue";
import { ref, watch, computed } from "vue";

const props = defineProps({
  show: { type: Boolean, default: false },
  client_case: { type: Object, required: true },
  actions: { type: Array, default: () => [] },
  contractUuid: { type: String, default: null },
  phoneMode: { type: Boolean, default: false },
  documents: { type: Array, default: null },
  contracts: { type: Array, default: null },
});

const page = usePage();

const decisions = ref(
  Array.isArray(props.actions) && props.actions.length > 0
    ? props.actions[0].decisions || []
    : []
);

const emit = defineEmits(["close", "saved"]);
const close = () => emit("close");

// Using Inertia's useForm for API calls, but wrapping fields with shadcn-vue components
const form = useInertiaForm({
  due_date: null,
  amount: null,
  note: "",
  action_id:
    Array.isArray(props.actions) && props.actions.length > 0 ? props.actions[0].id : null,
  decision_id:
    Array.isArray(props.actions) &&
    props.actions.length > 0 &&
    Array.isArray(props.actions[0].decisions) &&
    props.actions[0].decisions.length > 0
      ? props.actions[0].decisions[0].id
      : null,
  contract_uuids: props.contractUuid ? [props.contractUuid] : [],
  send_auto_mail: true,
  attach_documents: false,
  attachment_document_ids: [],
});

watch(
  () => props.actions,
  (list) => {
    if (!Array.isArray(list) || list.length === 0) {
      decisions.value = [];
      form.action_id = null;
      form.decision_id = null;
      return;
    }
    if (!form.action_id) {
      form.action_id = list[0].id;
    }
    const found = list.find((el) => el.id === form.action_id) || list[0];
    decisions.value = Array.isArray(found.decisions) ? found.decisions : [];
    if (!form.decision_id && decisions.value.length > 0) {
      form.decision_id = decisions.value[0].id;
    }
  },
  { immediate: true }
);

watch(
  () => form.action_id,
  (action_id) => {
    const a = Array.isArray(props.actions)
      ? props.actions.find((el) => el.id === action_id)
      : null;
    decisions.value = Array.isArray(a?.decisions) ? a.decisions : [];
    form.decision_id = decisions.value[0]?.id ?? null;
    form.send_auto_mail = true;
  }
);

watch(
  () => props.contractUuid,
  (cu) => {
    form.contract_uuids = cu ? [cu] : [];
  }
);

watch(
  () => props.show,
  (visible) => {
    if (visible) {
      form.contract_uuids = props.contractUuid ? [props.contractUuid] : [];
    }
  }
);

const store = async () => {
  const formatDateForSubmit = (value) => {
    if (!value) return null;
    const d = value instanceof Date ? value : new Date(value);
    if (isNaN(d.getTime())) return null;
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, "0");
    const day = String(d.getDate()).padStart(2, "0");
    return `${y}-${m}-${day}`;
  };

  const contractUuids =
    Array.isArray(form.contract_uuids) && form.contract_uuids.length > 0
      ? form.contract_uuids
      : null;

  const isMultipleContracts = contractUuids && contractUuids.length > 1;

  form
    .transform((data) => ({
      ...data,
      phone_view: props.phoneMode,
      due_date: formatDateForSubmit(data.due_date),
      contract_uuids: contractUuids,
      create_for_all_contracts: isMultipleContracts,
      attachment_document_ids:
        templateAllowsAttachments.value && data.attach_documents && !isMultipleContracts
          ? data.attachment_document_ids
          : [],
    }))
    .post(route("clientCase.activity.store", props.client_case), {
      onSuccess: () => {
        close();
        form.reset("due_date", "amount", "note", "contract_uuids");
        emit("saved");
      },
    });
};

const currentDecision = () => {
  if (!Array.isArray(decisions.value) || decisions.value.length === 0) {
    return null;
  }
  return (
    decisions.value.find((d) => d.id === form.decision_id) || decisions.value[0] || null
  );
};
const showSendAutoMail = () => {
  const d = currentDecision();
  return !!(d && d.auto_mail && d.email_template_id);
};

const templateAllowsAttachments = computed(() => {
  const d = currentDecision();
  const tmpl = d?.email_template || d?.emailTemplate || null;
  return !!(tmpl && tmpl.allow_attachments);
});

const autoMailRequiresContract = computed(() => {
  const d = currentDecision();
  if (!d) return false;
  const tmpl = d.email_template || d.emailTemplate || null;
  const types = Array.isArray(tmpl?.entity_types) ? tmpl.entity_types : [];
  return types.includes("contract");
});

const contractItems = computed(() => {
  return pageContracts.value.map((c) => ({
    value: c.uuid,
    label: `${c.reference}${c.name ? ` - ${c.name}` : ""}`,
  }));
});

const autoMailDisabled = computed(() => {
  if (!showSendAutoMail()) return false;

  // Disable if multiple contracts selected
  if (form.contract_uuids && form.contract_uuids.length > 1) return true;

  // Disable if template requires contract but none selected
  if (
    autoMailRequiresContract.value &&
    (!form.contract_uuids || form.contract_uuids.length === 0)
  ) {
    return true;
  }

  return false;
});

const autoMailDisabledHint = computed(() => {
  if (!showSendAutoMail()) return "";

  if (form.contract_uuids && form.contract_uuids.length > 1) {
    return "Avtomatska e-pošta ni na voljo pri več pogodbah.";
  }

  if (
    autoMailRequiresContract.value &&
    (!form.contract_uuids || form.contract_uuids.length === 0)
  ) {
    return "Ta e-poštna predloga zahteva pogodbo. Najprej izberite pogodbo.";
  }

  return "";
});
watch(
  () => autoMailDisabled.value,
  (disabled) => {
    if (disabled) {
      form.send_auto_mail = false;
    }
  }
);

const isToday = (val) => {
  try {
    if (!val) return false;
    let d;
    if (val instanceof Date) {
      d = val;
    } else if (typeof val === "string") {
      const s = val.includes("T") ? val : val.replace(" ", "T");
      d = new Date(s);
      if (isNaN(d.getTime())) {
        const m = val.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?/);
        if (m) {
          const [_, yy, mm, dd, hh, mi, ss] = m;
          d = new Date(
            Number(yy),
            Number(mm) - 1,
            Number(dd),
            Number(hh),
            Number(mi),
            Number(ss || "0")
          );
        }
      }
    } else if (typeof val === "number") {
      d = new Date(val);
    } else {
      return false;
    }
    if (isNaN(d.getTime())) return false;
    const today = new Date();
    return (
      d.getFullYear() === today.getFullYear() &&
      d.getMonth() === today.getMonth() &&
      d.getDate() === today.getDate()
    );
  } catch {
    return false;
  }
};

const docsSource = computed(() => {
  if (Array.isArray(props.documents)) {
    return props.documents;
  }
  const propsVal = page?.props?.value || {};
  return Array.isArray(propsVal.documents) ? propsVal.documents : [];
});

const availableContractDocs = computed(() => {
  if (!form.contract_uuids || form.contract_uuids.length === 0) return [];
  // Only show docs if exactly one contract is selected
  if (form.contract_uuids.length > 1) return [];
  const selectedUuid = form.contract_uuids[0];
  const docs = docsSource.value;
  const all = docs.filter((d) => d.contract_uuid === selectedUuid);
  if (!props.phoneMode) return all;
  return all.filter((d) => {
    const mime = (d.mime_type || "").toLowerCase();
    const isImage =
      mime.startsWith("image/") ||
      ["jpg", "jpeg", "png", "gif", "webp", "heic", "heif"].includes(
        (d.extension || "").toLowerCase()
      );
    return isImage && isToday(d.created_at || d.createdAt);
  });
});

const pageContracts = computed(() => {
  if (Array.isArray(props.contracts)) {
    return props.contracts;
  }
  if (props.contracts?.data) {
    return props.contracts.data;
  }
  const propsVal = page?.props?.value || {};
  if (propsVal.contracts?.data) {
    return propsVal.contracts.data;
  }
  return Array.isArray(propsVal.contracts) ? propsVal.contracts : [];
});

watch(
  [
    () => props.phoneMode,
    () => templateAllowsAttachments.value,
    () => form.contract_uuids,
    () => form.decision_id,
    () => availableContractDocs.value.length,
  ],
  () => {
    if (!props.phoneMode) return;
    if (!templateAllowsAttachments.value) return;
    if (!form.contract_uuids || form.contract_uuids.length !== 1) return;
    const docs = availableContractDocs.value;
    if (docs.length === 0) return;
    form.attach_documents = true;
    if (
      !Array.isArray(form.attachment_document_ids) ||
      form.attachment_document_ids.length === 0
    ) {
      form.attachment_document_ids = docs.map((d) => d.id);
    }
  }
);
</script>

<template>
  <CreateDialog
    :show="show"
    title="Dodaj aktivnost"
    confirm-text="Shrani"
    :processing="form.processing"
    @close="close"
    @confirm="store"
  >
    <form @submit.prevent="store">
      <div class="space-y-4">
        <div class="space-y-2">
          <Label>Akcija</Label>
          <Select v-model="form.action_id" :disabled="!actions || !actions.length">
            <SelectTrigger>
              <SelectValue placeholder="Izberi akcijo" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem v-for="a in actions" :key="a.id" :value="a.id">
                {{ a.name }}
              </SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div class="space-y-2">
          <Label>Odločitev</Label>
          <Select v-model="form.decision_id" :disabled="!decisions || !decisions.length">
            <SelectTrigger>
              <SelectValue placeholder="Izberi odločitev" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem v-for="d in decisions" :key="d.id" :value="d.id">
                {{ d.name }}
              </SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div class="space-y-2">
          <Label>Pogodbe</Label>
          <AppMultiSelect
            v-model="form.contract_uuids"
            :items="contractItems"
            placeholder="Izberi pogodbe (neobvezno)"
            search-placeholder="Išči pogodbo..."
            empty-text="Ni pogodb."
            :clearable="true"
            :show-selected-chips="true"
          />
          <p
            v-if="form.contract_uuids && form.contract_uuids.length > 1"
            class="text-xs text-muted-foreground"
          >
            Bo ustvarjenih {{ form.contract_uuids.length }} aktivnosti (ena za vsako
            pogodbo).
          </p>
        </div>

        <div class="space-y-2">
          <Label for="activityNote">Opomba</Label>
          <Textarea
            id="activityNote"
            v-model="form.note"
            class="block w-full max-h-72"
            placeholder="Opomba"
          />
        </div>

        <div class="space-y-2">
          <Label for="activityDueDate">Datum zapadlosti</Label>
          <DatePicker
            id="activityDueDate"
            v-model="form.due_date"
            format="dd.MM.yyyy"
            :error="form.errors.due_date"
          />
        </div>

        <div class="space-y-2">
          <Label for="activityAmount">Znesek</Label>
          <CurrencyInput
            id="activityAmount"
            v-model="form.amount"
            :precision="{ min: 0, max: 4 }"
            placeholder="0,00"
            class="w-full"
          />
        </div>

        <div v-if="showSendAutoMail()" class="space-y-2">
          <div class="flex items-center justify-between">
            <div class="flex items-center space-x-2">
              <Switch v-model="form.send_auto_mail" :disabled="autoMailDisabled" />
              <Label class="cursor-pointer">Send auto email</Label>
            </div>
          </div>
          <p v-if="autoMailDisabled" class="text-xs text-amber-600">
            {{ autoMailDisabledHint }}
          </p>

          <div
            v-if="
              templateAllowsAttachments &&
              form.contract_uuids &&
              form.contract_uuids.length === 1
            "
            class="mt-3"
          >
            <label class="inline-flex items-center gap-2">
              <Switch v-model="form.attach_documents" />
              <span class="text-sm">Dodaj priponke iz izbrane pogodbe</span>
            </label>
            <div
              v-if="form.attach_documents"
              class="mt-2 border rounded p-2 max-h-48 overflow-auto"
            >
              <div class="text-xs text-gray-600 mb-2">
                Izberite dokumente, ki bodo poslani kot priponke:
              </div>
              <div class="space-y-1">
                <template v-for="c in pageContracts" :key="c.uuid || c.id">
                  <div v-if="c.uuid === form.contract_uuids[0]">
                    <div class="font-medium text-sm text-gray-700 mb-1">
                      Pogodba {{ c.reference }}
                    </div>
                    <div class="space-y-1">
                      <div
                        v-for="doc in availableContractDocs"
                        :key="doc.uuid || doc.id"
                        class="flex items-center max-w-sm gap-2 text-sm"
                      >
                        <Switch
                          :model-value="form.attachment_document_ids.includes(doc.id)"
                          @update:model-value="
                            (checked) => {
                              if (checked) {
                                if (!form.attachment_document_ids.includes(doc.id)) {
                                  form.attachment_document_ids.push(doc.id);
                                }
                              } else {
                                form.attachment_document_ids = form.attachment_document_ids.filter(
                                  (id) => id !== doc.id
                                );
                              }
                            }
                          "
                        />
                        <div class="wrap-anywhere">
                          <p>
                            <span>{{ doc.name }}.{{ doc.extension }}</span>
                          </p>
                          <span class="text-xs text-gray-400"
                            >({{ doc.extension?.toUpperCase() || "" }},
                            {{ (doc.size / 1024 / 1024).toFixed(2) }} MB)</span
                          >
                        </div>
                      </div>
                    </div>
                  </div>
                </template>
                <div
                  v-if="availableContractDocs.length === 0"
                  class="text-sm text-gray-500"
                >
                  Ni dokumentov, povezanih s to pogodbo.
                </div>
              </div>
            </div>
          </div>
        </div>

        <ActionMessage :on="form.recentlySuccessful" class="text-sm text-green-600">
          Shranjuje.
        </ActionMessage>
      </div>
    </form>
  </CreateDialog>
</template>
