<script setup>
// Create a home charger from one on a connected charger service (Anker Solix or
// Greencell today; the endpoints are generic, so the next service needs no
// changes here).
//
// Shorter than the car import on purpose: a charger is a name, a serial and the
// hardware behind it, and the service's list already carries all three. There is
// nothing to choose about what to pull, so the whole screen is pick one, press
// Import.
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"]);

const providers = ref([]);
const provider = ref("");
const chargers = ref([]);
const selectedId = ref("");
const name = ref("");
const loading = ref(true);
const loadingChargers = 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("");

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

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

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

  loadingChargers.value = true;
  error.value = "";
  try {
    const res = await api.listProviderChargers(provider.value);
    chargers.value = res.chargers || [];
    detail.value = res.unavailable ? res.detail || "" : "";
    // Preselect the first charger that isn't here already — with one charger on
    // the account that is the whole selection step.
    selectedId.value = chargers.value.find((c) => !c.linkedChargerId)?.id || "";
  } catch (e) {
    error.value = e.message;
  } finally {
    loadingChargers.value = false;
  }
}

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

function subtitle(c) {
  return [c.vendor, c.model, c.siteName].filter(Boolean).join(" · ");
}

async function submit() {
  if (!canImport.value) return;
  importing.value = true;
  error.value = "";
  try {
    const res = await api.importProviderCharger(provider.value, {
      chargerId: selected.value.id,
      name: name.value.trim(),
    });
    emit("saved", res.charger);
  } catch (e) {
    error.value = e.message;
  } finally {
    importing.value = false;
  }
}

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

<template>
  <Modal :title="t('forms.importCharger.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.importCharger.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.importCharger.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>

      <!-- Chargers on the account -->
      <div>
        <label class="dh-label">{{ t("forms.importCharger.selectCharger") }}</label>
        <p v-if="loadingChargers" class="text-sm text-muted">{{ t("forms.importCharger.loadingChargers") }}</p>
        <p v-else-if="!detail && chargers.length === 0" class="text-sm text-muted">
          {{ t("forms.importCharger.noChargers") }}
        </p>

        <ul v-else-if="chargers.length" class="space-y-2">
          <li v-for="c in chargers" :key="c.id">
            <label
              class="flex cursor-pointer items-start gap-3 rounded-control border p-3 transition-colors"
              :class="selectedId === c.id ? 'border-accent bg-sunken' : 'border-subtle hover:bg-sunken'">
              <input
                v-model="selectedId"
                type="radio"
                :value="c.id"
                :disabled="!!c.linkedChargerId"
                class="mt-1"
              />
              <span class="min-w-0 flex-1">
                <span class="block truncate font-medium text-strong">{{ c.name || c.id }}</span>
                <span v-if="subtitle(c)" class="block truncate text-xs text-muted">{{ subtitle(c) }}</span>
                <span class="data mt-0.5 block truncate text-xs text-muted">{{ c.id }}</span>
                <span v-if="c.linkedChargerId" class="mt-1 inline-flex items-center gap-2">
                  <span class="dh-badge dh-badge-neutral">{{ t("forms.importCharger.alreadyImported") }}</span>
                </span>
                <span v-else-if="c.online === false" class="mt-1 inline-flex">
                  <span class="dh-badge dh-badge-warning">{{ t("settings.integrations.chargerOffline") }}</span>
                </span>
              </span>
            </label>
          </li>
        </ul>
      </div>

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

      <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.importCharger.submit") }}
        </button>
      </div>
    </form>
  </Modal>
</template>
