<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 Modal from "./Modal.vue";

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

const isEdit = !!props.part;
const saving = ref(false);
const error = ref("");
const form = ref({
  name: props.part?.name ?? "",
  partNumber: props.part?.partNumber ?? "",
  category: props.part?.category ?? "",
  notes: props.part?.notes ?? "",
});

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

async function submit() {
  saving.value = true;
  error.value = "";
  try {
    const payload = {
      car: props.carId,
      name: form.value.name.trim(),
      partNumber: form.value.partNumber.trim(),
      category: form.value.category.trim(),
      notes: form.value.notes.trim(),
    };
    const saved = isEdit
      ? await api.updatePart(props.part.id, payload)
      : await api.createPart(payload);
    emit("saved", await applyAttachment(api.files.parts, saved, {
      file: file.value,
      remove: removeFile.value,
    }));
  } catch (e) {
    error.value = e.message;
  } finally {
    saving.value = false;
  }
}
</script>

<template>
  <Modal :title="isEdit ? t('forms.part.editTitle') : t('forms.part.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.part.name") }}</label>
        <input v-model="form.name" required :placeholder="t('forms.part.namePlaceholder')" class="dh-input" />
      </div>
      <div>
        <label class="dh-label">{{ t("forms.part.partNumber") }}</label>
        <input v-model="form.partNumber" placeholder="04152-YZZA7" class="dh-input data" />
      </div>
      <div>
        <label class="dh-label">{{ t("forms.part.notes") }}</label>
        <input v-model="form.notes" :placeholder="t('forms.part.notesPlaceholder')" class="dh-input" />
      </div>
      <AttachmentField v-model:file="file" v-model:remove="removeFile" :record="part" :legend="t('forms.part.attachmentLegend')" />
      <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.part.submit") }}
        </button>
      </div>
    </form>
  </Modal>
</template>
