<script setup>
import { ref, computed } from "vue";
import { api } from "../api";
import { formatMoney } from "../lib/format.js";
import { applyAttachment } from "../lib/attachment.js";
import { t, tSplit } 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 },
  entry: { type: Object, default: null },
});
const emit = defineEmits(["saved", "close"]);

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

const TYPE_VALUES = ["repair", "inspection", "bodywork", "tyres", "diagnostics", "recall", "warranty", "other"];
const STATUS_VALUES = ["scheduled", "in_progress", "completed"];

const form = ref({
  date: props.entry ? toDateInput(props.entry.date) : new Date().toISOString().slice(0, 10),
  km: props.entry?.km ?? "",
  type: props.entry?.type ?? "repair",
  status: props.entry?.status ?? "completed",
  workshop: props.entry?.workshop ?? "",
  location: props.entry?.location ?? "",
  description: props.entry?.description ?? "",
  partsUsed: props.entry?.partsUsed ?? "",
  laborCost: props.entry?.laborCost ?? "",
  partsCost: props.entry?.partsCost ?? "",
  invoiceNumber: props.entry?.invoiceNumber ?? "",
  warrantyUntil: props.entry?.warrantyUntil ? toDateInput(props.entry.warrantyUntil) : "",
  notes: props.entry?.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);
}

const totalCost = computed(() => {
  const total = Number(form.value.laborCost || 0) + Number(form.value.partsCost || 0);
  return total > 0 ? formatMoney(total) : null;
});

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

function payload() {
  return {
    car: props.carId,
    date: new Date(form.value.date).toISOString(),
    km: form.value.km ? Number(form.value.km) : 0,
    type: form.value.type,
    status: form.value.status,
    workshop: form.value.workshop.trim(),
    location: form.value.location.trim(),
    description: form.value.description.trim(),
    partsUsed: form.value.partsUsed.trim(),
    laborCost: form.value.laborCost ? Number(form.value.laborCost) : 0,
    partsCost: form.value.partsCost ? Number(form.value.partsCost) : 0,
    invoiceNumber: form.value.invoiceNumber.trim(),
    warrantyUntil: form.value.warrantyUntil ? new Date(form.value.warrantyUntil).toISOString() : null,
    notes: form.value.notes.trim(),
  };
}
</script>

<template>
  <Modal :title="isEdit ? t('forms.maintenance.editTitle') : t('forms.maintenance.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 class="grid grid-cols-2 gap-2">
        <div>
          <label class="dh-label">{{ t("forms.maintenance.date") }}</label>
          <DateField v-model="form.date" required />
        </div>
        <div>
          <label class="dh-label">{{ t("forms.maintenance.odometer") }}</label>
          <input v-model="form.km" type="number" min="0" placeholder="16138" class="dh-input data" />
        </div>
      </div>

      <div class="grid grid-cols-2 gap-2">
        <div>
          <label class="dh-label">{{ t("forms.maintenance.type") }}</label>
          <select v-model="form.type" class="dh-input">
            <option v-for="v in TYPE_VALUES" :key="v" :value="v">{{ t(`enums.maintenanceType.${v}`) }}</option>
          </select>
        </div>
        <div>
          <label class="dh-label">{{ t("forms.maintenance.status") }}</label>
          <select v-model="form.status" class="dh-input">
            <option v-for="v in STATUS_VALUES" :key="v" :value="v">{{ t(`enums.maintenanceStatus.${v}`) }}</option>
          </select>
        </div>
      </div>

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

      <div class="grid grid-cols-2 gap-2">
        <div>
          <label class="dh-label">{{ t("forms.maintenance.workshop") }}</label>
          <input v-model="form.workshop" placeholder="Auto Serwis Kowalski" class="dh-input" />
        </div>
        <div>
          <label class="dh-label">{{ t("forms.maintenance.location") }}</label>
          <input v-model="form.location" placeholder="Kraków" class="dh-input" />
        </div>
      </div>

      <div>
        <label class="dh-label">{{ t("forms.maintenance.partsUsed") }}</label>
        <input v-model="form.partsUsed" :placeholder="t('forms.maintenance.partsUsedPlaceholder')" class="dh-input" />
      </div>

      <div class="grid grid-cols-2 gap-2">
        <div>
          <label class="dh-label">{{ t("forms.maintenance.laborCost") }}</label>
          <input v-model="form.laborCost" type="number" step="0.01" min="0" class="dh-input data" />
        </div>
        <div>
          <label class="dh-label">{{ t("forms.maintenance.partsCost") }}</label>
          <input v-model="form.partsCost" type="number" step="0.01" min="0" class="dh-input data" />
        </div>
      </div>

      <p v-if="totalCost" class="text-xs text-muted">
        {{ tSplit("forms.maintenance.total", "total").before
        }}<span class="data text-strong">{{ totalCost }}</span>{{ tSplit("forms.maintenance.total", "total").after }}
      </p>

      <div class="grid grid-cols-2 gap-2">
        <div>
          <label class="dh-label">{{ t("forms.maintenance.invoiceNumber") }}</label>
          <input v-model="form.invoiceNumber" class="dh-input data" />
        </div>
        <div>
          <label class="dh-label">{{ t("forms.maintenance.warrantyUntil") }}</label>
          <DateField v-model="form.warrantyUntil" />
        </div>
      </div>

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

      <div>
        <label class="dh-label">{{ t("forms.maintenance.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.maintenance.submit") }}
        </button>
      </div>
    </form>
  </Modal>
</template>
