<script setup>
import { ref, computed, watch } from "vue";
import { useForm } from "@inertiajs/vue3";
import DialogModal from "@/Components/DialogModal.vue";

const props = defineProps({
  show: { type: Boolean, default: false },
  contract: { type: Object, default: null },
  clientCase: { type: Object, required: true },
});

const emit = defineEmits(["close"]);

const metaFields = ref([]);

// Extract meta fields when contract changes
watch(
  () => props.contract,
  (c) => {
    if (!c) {
      metaFields.value = [];
      return;
    }
    metaFields.value = extractMetaFields(c?.meta || {});
  },
  { immediate: true }
);

function extractMetaFields(meta, parentKey = "") {
  const results = [];
  const visit = (node, path) => {
    if (node === null || node === undefined) {
      return;
    }
    if (Array.isArray(node)) {
      node.forEach((el, idx) => visit(el, `${path}[${idx}]`));
      return;
    }
    if (typeof node === "object") {
      const hasValue = Object.prototype.hasOwnProperty.call(node, "value");
      const hasTitle = Object.prototype.hasOwnProperty.call(node, "title");
      if (hasValue || hasTitle) {
        const title = (node.title || path || "Meta").toString().trim();
        const type = node.type || (typeof node.value === "number" ? "number" : "text");
        results.push({
          path,
          title,
          value: node.value ?? "",
          type,
        });
        return;
      }
      for (const [k, v] of Object.entries(node)) {
        const newPath = path ? `${path}.${k}` : k;
        visit(v, newPath);
      }
      return;
    }
    if (path) {
      results.push({ path, title: path, value: node, type: "text" });
    }
  };
  visit(meta, "");
  return results;
}

const form = useForm({
  meta: {},
});

watch(
  () => props.show,
  (val) => {
    if (val && props.contract) {
      // Rebuild meta structure for form
      const metaObj = {};
      metaFields.value.forEach((field) => {
        setNestedValue(metaObj, field.path, {
          title: field.title,
          value: field.value,
          type: field.type,
        });
      });
      form.meta = metaObj;
    }
  }
);

function setNestedValue(obj, path, value) {
  const parts = path.split(/\.|\[|\]/).filter(Boolean);
  let current = obj;
  for (let i = 0; i < parts.length - 1; i++) {
    const part = parts[i];
    if (!current[part]) {
      const nextPart = parts[i + 1];
      current[part] = /^\d+$/.test(nextPart) ? [] : {};
    }
    current = current[part];
  }
  current[parts[parts.length - 1]] = value;
}

function updateFieldValue(field, newValue) {
  field.value = newValue;
}

function closeDialog() {
  emit("close");
}

function submitForm() {
  if (!props.contract?.uuid) return;

  // Rebuild meta object from fields
  const metaObj = {};
  metaFields.value.forEach((field) => {
    setNestedValue(metaObj, field.path, {
      title: field.title,
      value: field.value,
      type: field.type,
    });
  });

  form.meta = metaObj;

  form.patch(
    route("clientCase.contract.patchMeta", {
      client_case: props.clientCase.uuid,
      uuid: props.contract.uuid,
    }),
    {
      preserveScroll: true,
      onSuccess: () => {
        closeDialog();
      },
    }
  );
}

function formatInputType(type) {
  if (type === "date") return "date";
  if (type === "number") return "number";
  return "text";
}
</script>

<template>
  <DialogModal :show="show" max-width="2xl" @close="closeDialog">
    <template #title>
      Uredi meta podatke
      <span v-if="contract" class="text-gray-500 font-normal">
        - {{ contract.reference }}
      </span>
    </template>
    <template #content>
      <div v-if="metaFields.length === 0" class="text-sm text-gray-500">
        Ni meta podatkov za urejanje.
      </div>
      <div v-else class="space-y-3">
        <div
          v-for="(field, idx) in metaFields"
          :key="idx"
          class="grid grid-cols-3 gap-3 items-start"
        >
          <div class="col-span-1">
            <label class="block text-sm font-medium text-gray-700">
              {{ field.title }}
            </label>
            <div class="text-xs text-gray-400 mt-0.5">{{ field.path }}</div>
          </div>
          <div class="col-span-2">
            <input
              v-if="
                field.type !== 'text' || field.type === 'date' || field.type === 'number'
              "
              :type="formatInputType(field.type)"
              v-model="field.value"
              class="w-full rounded-md border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 text-sm"
            />
            <textarea
              v-else
              v-model="field.value"
              rows="2"
              class="w-full rounded-md border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 text-sm"
            ></textarea>
          </div>
        </div>
      </div>
      <div v-if="form.errors.meta" class="mt-3 text-sm text-red-600">
        {{ form.errors.meta }}
      </div>
    </template>
    <template #footer>
      <button
        type="button"
        class="px-4 py-2 text-sm rounded-md border border-gray-300 text-gray-700 bg-white hover:bg-gray-50 mr-2"
        @click="closeDialog"
      >
        Prekliči
      </button>
      <button
        type="button"
        class="px-4 py-2 text-sm rounded-md bg-indigo-600 text-white hover:bg-indigo-700 disabled:opacity-50"
        :disabled="form.processing || metaFields.length === 0"
        @click="submitForm"
      >
        Shrani
      </button>
    </template>
  </DialogModal>
</template>
