<script setup>
import { ref, computed } from "vue";
import { api } from "../api";
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 form = ref({
  date: props.entry ? toDateInput(props.entry.date) : new Date().toISOString().slice(0, 10),
  km: props.entry?.km ?? "",
  liters: props.entry?.liters ?? "",
  cost: props.entry?.cost ?? "",
  // A full tank is the common case and the one that makes the entry count
  // towards efficiency, so it is the default.
  fullTank: props.entry ? props.entry.fullTank : true,
  missedFill: props.entry ? props.entry.missedFill : false,
  station: props.entry?.station ?? "",
  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 pricePerLiter = computed(() => {
  const l = Number(form.value.liters);
  const c = Number(form.value.cost);
  if (!l || !c) return null;
  return (c / l).toFixed(3);
});

async function submit() {
  saving.value = true;
  error.value = "";
  try {
    const saved = await (isEdit ? api.updateFuel(props.entry.id, payload()) : api.createFuel(payload()));
    emit("saved", await applyAttachment(api.files.fuel, 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,
    liters: form.value.liters ? Number(form.value.liters) : 0,
    cost: form.value.cost ? Number(form.value.cost) : 0,
    fullTank: form.value.fullTank,
    missedFill: form.value.missedFill,
    station: form.value.station.trim(),
    notes: form.value.notes.trim(),
  };
}
</script>

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

      <div class="grid grid-cols-2 gap-2">
        <div>
          <label class="dh-label">{{ t("forms.fuel.liters") }}</label>
          <input v-model="form.liters" type="number" step="0.01" min="0.01" required placeholder="42.5" class="dh-input data" />
        </div>
        <div>
          <label class="dh-label">{{ t("forms.fuel.cost") }}</label>
          <input v-model="form.cost" type="number" step="0.01" min="0" placeholder="285.00" class="dh-input data" />
        </div>
      </div>

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

      <fieldset class="rounded-control border border-subtle p-3">
        <legend class="eyebrow px-1">{{ t("forms.fuel.tank") }}</legend>
        <label class="flex items-center gap-2 py-1 text-sm text-body">
          <input type="checkbox" v-model="form.fullTank" class="accent-[var(--accent)]" /> {{ t("forms.fuel.fullTank") }}
        </label>
        <label class="flex items-center gap-2 py-1 text-sm text-body">
          <input type="checkbox" v-model="form.missedFill" class="accent-[var(--accent)]" /> {{ t("forms.fuel.missedFill") }}
        </label>
        <p class="mt-1.5 text-xs text-muted">{{ t("forms.fuel.tankHint") }}</p>
      </fieldset>

      <div class="grid grid-cols-2 gap-2">
        <div>
          <label class="dh-label">{{ t("forms.fuel.station") }}</label>
          <input v-model="form.station" placeholder="Orlen" class="dh-input" />
        </div>
        <div>
          <label class="dh-label">{{ t("forms.fuel.notes") }}</label>
          <input v-model="form.notes" class="dh-input" />
        </div>
      </div>

      <AttachmentField v-model:file="file" v-model:remove="removeFile" :record="entry" :legend="t('forms.fuel.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.fuel.submit") }}
        </button>
      </div>
    </form>
  </Modal>
</template>
