<script setup>
// Create a car from a vehicle on a connected manufacturer account (MyToyota
// today; the endpoints are generic, so the next provider needs no changes here).
//
// The three steps are one screen on purpose: with a single connected service and
// one car on it, importing is two clicks — pick the vehicle, press Import — and
// the data checkboxes are there for the person who would rather type the plate
// themselves. Everything is checked by default, because "fetch what you can" is
// what someone importing a car is asking for.
import { ref, computed, onMounted, watch } from "vue";
import { api } from "../api";
import { t } from "../i18n";
import Modal from "./Modal.vue";

const emit = defineEmits(["saved", "close", "open-car"]);

const providers = ref([]);
const provider = ref("");
const vehicles = ref([]);
const selectedId = ref("");
const name = ref("");
const loading = ref(true);
const loadingVehicles = ref(false);
const importing = ref(false);
const error = ref("");
// Why the provider can't be used right now (not connected, org switch off, …).
// The server phrases this; the UI just shows it.
const detail = ref("");

// Every group on by default — see the note above.
const include = ref({ identity: true, fuelType: true, dates: true, odometer: true });

const connected = computed(() => providers.value.filter((p) => p.connected));
const current = computed(() => providers.value.find((p) => p.id === provider.value) || null);
const selected = computed(() => vehicles.value.find((v) => v.id === selectedId.value) || null);
const canImport = computed(() => !!selected.value && !selected.value.linkedCarId && !importing.value);

async function loadProviders() {
  loading.value = true;
  error.value = "";
  try {
    providers.value = await api.listVehicleProviders();
    provider.value = connected.value[0]?.id || providers.value[0]?.id || "";
  } catch (e) {
    error.value = e.message;
  } finally {
    loading.value = false;
  }
}

async function loadVehicles() {
  vehicles.value = [];
  selectedId.value = "";
  detail.value = "";
  if (!provider.value) return;
  if (!current.value?.connected) {
    detail.value = current.value?.detail || "";
    return;
  }

  loadingVehicles.value = true;
  error.value = "";
  try {
    const res = await api.listProviderVehicles(provider.value);
    vehicles.value = res.vehicles || [];
    detail.value = res.unavailable ? res.detail || "" : "";
    // Preselect the first vehicle that isn't in the garage already — with one
    // car on the account that is the whole selection step.
    selectedId.value = vehicles.value.find((v) => !v.linkedCarId)?.id || "";
  } catch (e) {
    error.value = e.message;
  } finally {
    loadingVehicles.value = false;
  }
}

// The name field tracks the selected vehicle until the user types their own.
const nameEdited = ref(false);
watch(selected, (v) => {
  if (!nameEdited.value) name.value = v?.name || "";
});
watch(provider, loadVehicles);

function subtitle(v) {
  return [v.make, v.model, v.year || ""].filter(Boolean).join(" ");
}

async function submit() {
  if (!canImport.value) return;
  importing.value = true;
  error.value = "";
  try {
    const res = await api.importProviderVehicle(provider.value, {
      vehicleId: selected.value.id,
      name: name.value.trim(),
      include: include.value,
    });
    emit("saved", res.car, res.warnings || []);
  } catch (e) {
    error.value = e.message;
  } finally {
    importing.value = false;
  }
}

onMounted(async () => {
  await loadProviders();
  await loadVehicles();
});
</script>

<template>
  <Modal :title="t('forms.import.title')" @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>
    <p v-if="loading" class="text-sm text-muted">{{ t("common.loading") }}</p>

    <template v-else-if="providers.length === 0">
      <p class="text-sm text-muted">{{ t("forms.import.noProviders") }}</p>
      <div class="mt-4 flex justify-end">
        <button type="button" class="dh-btn dh-btn-ghost" @click="emit('close')">{{ t("common.cancel") }}</button>
      </div>
    </template>

    <form v-else class="space-y-4" @submit.prevent="submit">
      <p class="text-sm text-muted">{{ t("forms.import.subtitle") }}</p>

      <!-- Service picker. Hidden while there is only one to pick. -->
      <div v-if="providers.length > 1">
        <label class="dh-label">{{ t("forms.import.service") }}</label>
        <select v-model="provider" class="dh-input">
          <option v-for="p in providers" :key="p.id" :value="p.id" :disabled="!p.connected">
            {{ p.label }}{{ p.connected ? "" : " — " + t("forms.import.notConnected") }}
          </option>
        </select>
      </div>

      <p v-if="detail" class="rounded-control bg-warning-soft px-3 py-2 text-sm text-warning">{{ detail }}</p>

      <!-- Vehicles on the account -->
      <div>
        <label class="dh-label">{{ t("forms.import.selectVehicle") }}</label>
        <p v-if="loadingVehicles" class="text-sm text-muted">{{ t("forms.import.loadingVehicles") }}</p>
        <p v-else-if="!detail && vehicles.length === 0" class="text-sm text-muted">{{ t("forms.import.noVehicles") }}</p>

        <ul v-else-if="vehicles.length" class="space-y-2">
          <li v-for="v in vehicles" :key="v.id">
            <label
              class="flex cursor-pointer items-start gap-3 rounded-control border p-3 transition-colors"
              :class="selectedId === v.id ? 'border-accent bg-sunken' : 'border-subtle hover:bg-sunken'">
              <input
                v-model="selectedId"
                type="radio"
                :value="v.id"
                :disabled="!!v.linkedCarId"
                class="mt-1"
              />
              <span class="min-w-0 flex-1">
                <span class="block truncate font-medium text-strong">{{ v.name }}</span>
                <span class="block truncate text-xs text-muted">{{ subtitle(v) }}</span>
                <span v-if="v.registration || v.vin" class="data mt-0.5 block truncate text-xs text-muted">
                  {{ [v.registration, v.vin].filter(Boolean).join(" · ") }}
                </span>
                <span v-if="v.linkedCarId" class="mt-1 inline-flex items-center gap-2">
                  <span class="dh-badge dh-badge-neutral">{{ t("forms.import.alreadyInGarage") }}</span>
                  <button
                    type="button"
                    class="text-xs font-medium text-brandtext hover:underline"
                    @click.prevent="emit('open-car', v.linkedCarId)">
                    {{ t("common.open") }}
                  </button>
                </span>
              </span>
            </label>
          </li>
        </ul>
      </div>

      <template v-if="selected">
        <div>
          <label class="dh-label">{{ t("forms.import.name") }}</label>
          <input v-model="name" required class="dh-input" @input="nameEdited = true" />
        </div>

        <fieldset class="rounded-control border border-subtle p-3">
          <legend class="eyebrow px-1">{{ t("forms.import.dataTitle") }}</legend>
          <p class="mb-2 text-xs text-muted">{{ t("forms.import.dataHint") }}</p>
          <label class="flex items-center gap-2 py-1 text-sm text-body">
            <input v-model="include.identity" type="checkbox" />
            <span>{{ t("forms.import.includeIdentity") }}</span>
          </label>
          <label class="flex items-center gap-2 py-1 text-sm text-body">
            <input v-model="include.fuelType" type="checkbox" />
            <span>{{ t("forms.import.includeFuelType") }}</span>
          </label>
          <label class="flex items-center gap-2 py-1 text-sm text-body">
            <input v-model="include.dates" type="checkbox" />
            <span>{{ t("forms.import.includeDates") }}</span>
          </label>
          <label class="flex items-center gap-2 py-1 text-sm text-body">
            <input v-model="include.odometer" type="checkbox" />
            <span>{{ t("forms.import.includeOdometer") }}</span>
          </label>
          <p class="mt-2 text-xs text-muted">
            {{ t("forms.import.moreData", { label: current?.label || "" }) }}
          </p>
        </fieldset>
      </template>

      <div class="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="!canImport" class="dh-btn dh-btn-primary">
          {{ importing ? t("forms.import.importing") : t("forms.import.submit") }}
        </button>
      </div>
    </form>
  </Modal>
</template>
