<script setup>
// One charging session. The EV counterpart of FuelFormModal and deliberately
// the same form: energy in place of litres, and a charge to the car's usual full
// point in place of the full tank, which is what makes the session count towards
// the kWh/100km figures.
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 ?? "",
  kwh: props.entry?.kwh ?? "",
  cost: props.entry?.cost ?? "",
  // A charge to the usual full point is the one that makes the session count
  // towards efficiency, so it is the default — as the full tank is for fuel.
  fullCharge: props.entry ? props.entry.fullCharge : true,
  missedSession: props.entry ? props.entry.missedSession : false,
  location: props.entry?.location ?? "",
  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 pricePerKwh = computed(() => {
  const k = Number(form.value.kwh);
  const c = Number(form.value.cost);
  if (!k || !c) return null;
  return (c / k).toFixed(3);
});

async function submit() {
  saving.value = true;
  error.value = "";
  try {
    const saved = await (isEdit
      ? api.updateCharging(props.entry.id, payload())
      : api.createCharging(payload()));
    emit("saved", await applyAttachment(api.files.charging, 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,
    kwh: form.value.kwh ? Number(form.value.kwh) : 0,
    cost: form.value.cost ? Number(form.value.cost) : 0,
    fullCharge: form.value.fullCharge,
    missedSession: form.value.missedSession,
    location: form.value.location.trim(),
    notes: form.value.notes.trim(),
  };
}
</script>

<template>
  <Modal :title="isEdit ? t('forms.charging.editTitle') : t('forms.charging.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.charging.date") }}</label>
          <DateField v-model="form.date" required />
        </div>
        <div>
          <label class="dh-label">{{ t("forms.charging.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.charging.kwh") }}</label>
          <input v-model="form.kwh" type="number" step="0.01" min="0.01" required placeholder="42.5" class="dh-input data" />
        </div>
        <div>
          <label class="dh-label">{{ t("forms.charging.cost") }}</label>
          <input v-model="form.cost" type="number" step="0.01" min="0" placeholder="85.00" class="dh-input data" />
        </div>
      </div>

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

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

      <div class="grid grid-cols-2 gap-2">
        <div>
          <label class="dh-label">{{ t("forms.charging.location") }}</label>
          <input v-model="form.location" :placeholder="t('forms.charging.locationPlaceholder')" class="dh-input" />
        </div>
        <div>
          <label class="dh-label">{{ t("forms.charging.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.charging.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.charging.submit") }}
        </button>
      </div>
    </form>
  </Modal>
</template>
