<script setup>
import { ref } from "vue";
import { api } from "../api";
import { applyAttachment } from "../lib/attachment.js";
import { t } from "../i18n";
import AttachmentField from "./AttachmentField.vue";
import DateField from "./DateField.vue";
import Modal from "./Modal.vue";

const props = defineProps({
  carId: { type: String, required: true },
  doc: { type: Object, default: null },
});
const emit = defineEmits(["saved", "close"]);

const isEdit = !!props.doc;
const saving = ref(false);
const error = ref("");

const TYPE_VALUES = ["insurance", "pollution", "registration", "inspection", "roadTax", "warranty", "other"];

const form = ref({
  type: props.doc?.type ?? "insurance",
  title: props.doc?.title ?? "",
  provider: props.doc?.provider ?? "",
  reference: props.doc?.reference ?? "",
  issueDate: props.doc?.issueDate ? toDateInput(props.doc.issueDate) : "",
  expiryDate: props.doc?.expiryDate ? toDateInput(props.doc.expiryDate) : "",
  cost: props.doc?.cost ?? "",
  notes: props.doc?.notes ?? "",
});

const file = ref(null);
const removeFile = ref(false);

function toDateInput(value) {
  const d = new Date(value);
  return isNaN(d) ? "" : d.toISOString().slice(0, 10);
}

async function submit() {
  saving.value = true;
  error.value = "";
  try {
    const saved = isEdit
      ? await api.updateDocument(props.doc.id, payload())
      : await api.createDocument(payload());
    emit("saved", await applyAttachment(api.files.documents, saved, {
      file: file.value,
      remove: removeFile.value,
    }));
  } catch (e) {
    error.value = e.message;
  } finally {
    saving.value = false;
  }
}

function payload() {
  return {
    car: props.carId,
    type: form.value.type,
    title: form.value.title.trim(),
    provider: form.value.provider.trim(),
    reference: form.value.reference.trim(),
    issueDate: form.value.issueDate ? new Date(form.value.issueDate).toISOString() : null,
    expiryDate: form.value.expiryDate ? new Date(form.value.expiryDate).toISOString() : null,
    cost: form.value.cost ? Number(form.value.cost) : 0,
    notes: form.value.notes.trim(),
  };
}
</script>

<template>
  <Modal :title="isEdit ? t('forms.document.editTitle') : t('forms.document.addTitle')" @close="emit('close')">
    <p v-if="error" class="mb-3 rounded-control bg-danger-soft px-3 py-2 text-sm font-medium text-danger">{{ error }}</p>
    <form class="space-y-3" @submit.prevent="submit">
      <div>
        <label class="dh-label">{{ t("forms.document.type") }}</label>
        <select v-model="form.type" class="dh-input">
          <option v-for="v in TYPE_VALUES" :key="v" :value="v">{{ t(`enums.documentType.${v}`) }}</option>
        </select>
      </div>

      <div>
        <label class="dh-label">{{ t("forms.document.title") }}</label>
        <input v-model="form.title" required :placeholder="t('forms.document.titlePlaceholder')" class="dh-input" />
      </div>

      <div class="grid grid-cols-2 gap-2">
        <div>
          <label class="dh-label">{{ t("forms.document.provider") }}</label>
          <input v-model="form.provider" placeholder="PZU" class="dh-input" />
        </div>
        <div>
          <label class="dh-label">{{ t("forms.document.reference") }}</label>
          <input v-model="form.reference" class="dh-input data" />
        </div>
      </div>

      <div class="grid grid-cols-2 gap-2">
        <div>
          <label class="dh-label">{{ t("forms.document.issued") }}</label>
          <DateField v-model="form.issueDate" />
        </div>
        <div>
          <label class="dh-label">{{ t("forms.document.renewalDate") }}</label>
          <DateField v-model="form.expiryDate" />
        </div>
      </div>
      <p class="text-xs text-muted">{{ t("forms.document.renewalHint") }}</p>

      <div>
        <label class="dh-label">{{ t("forms.document.cost") }}</label>
        <input v-model="form.cost" type="number" step="0.01" min="0" class="dh-input data" />
      </div>

      <AttachmentField v-model:file="file" v-model:remove="removeFile" :record="doc" :legend="t('forms.document.attachmentLegend')" />

      <div>
        <label class="dh-label">{{ t("forms.document.notes") }}</label>
        <input v-model="form.notes" class="dh-input" />
      </div>

      <div class="mt-4 flex justify-end gap-2">
        <button type="button" class="dh-btn dh-btn-ghost" @click="emit('close')">{{ t("common.cancel") }}</button>
        <button type="submit" :disabled="saving" class="dh-btn dh-btn-primary">
          {{ saving ? t("common.saving") : isEdit ? t("common.saveChanges") : t("forms.document.submit") }}
        </button>
      </div>
    </form>
  </Modal>
</template>
