<script setup>
import { ref, onMounted } from "vue";
import { api } from "../api";
import { t } from "../i18n";
import Modal from "./Modal.vue";

const props = defineProps({ car: { type: Object, required: true } });
const emit = defineEmits(["close"]);

const shares = ref([]);
const loading = ref(true);
const error = ref("");

const email = ref("");
const permission = ref("read");
const submitting = ref(false);

async function load() {
  loading.value = true;
  error.value = "";
  try {
    shares.value = await api.listCarShares(props.car.id);
  } catch (e) {
    error.value = e.message;
  } finally {
    loading.value = false;
  }
}

async function addShare() {
  const addr = email.value.trim();
  if (!addr) return;
  submitting.value = true;
  error.value = "";
  try {
    await api.addCarShare(props.car.id, addr, permission.value);
    email.value = "";
    permission.value = "read";
    await load();
  } catch (e) {
    error.value = e.message;
  } finally {
    submitting.value = false;
  }
}

// Change an existing grant's permission (upsert by the same email).
async function setPermission(share, value) {
  error.value = "";
  try {
    await api.addCarShare(props.car.id, share.user.email, value);
    await load();
  } catch (e) {
    error.value = e.message;
  }
}

async function removeShare(share) {
  error.value = "";
  try {
    await api.removeCarShare(props.car.id, share.user.id);
    await load();
  } catch (e) {
    error.value = e.message;
  }
}

onMounted(load);
</script>

<template>
  <Modal :title="t('forms.share.title', { name: car.name })" @close="emit('close')">
    <p class="mb-4 text-sm text-muted">{{ t("forms.share.body") }}</p>

    <p v-if="error" class="mb-3 rounded-control bg-danger-soft px-3 py-2 text-sm font-medium text-danger">{{ error }}</p>

    <!-- Add form -->
    <form class="mb-4 flex items-end gap-2" @submit.prevent="addShare">
      <div class="flex-1">
        <label class="dh-label">{{ t("forms.share.userEmail") }}</label>
        <input v-model="email" type="email" required placeholder="person@example.com" class="dh-input" />
      </div>
      <select v-model="permission" class="dh-input w-auto">
        <option value="read">{{ t("forms.share.read") }}</option>
        <option value="write">{{ t("forms.share.write") }}</option>
      </select>
      <button type="submit" :disabled="submitting" class="dh-btn dh-btn-primary">{{ t("forms.share.submit") }}</button>
    </form>

    <!-- Current shares -->
    <div>
      <h3 class="mb-2 text-sm font-semibold text-strong">{{ t("forms.share.peopleWithAccess") }}</h3>
      <p v-if="loading" class="text-sm text-muted">{{ t("common.loading") }}</p>
      <p v-else-if="shares.length === 0" class="text-sm text-muted">{{ t("forms.share.notShared") }}</p>
      <ul v-else class="divide-y divide-subtle">
        <li v-for="s in shares" :key="s.user.id" class="flex items-center justify-between gap-2 py-2">
          <div class="min-w-0">
            <p class="truncate text-sm font-medium text-strong">{{ s.user.name || s.user.email }}</p>
            <p v-if="s.user.name" class="truncate text-xs text-muted">{{ s.user.email }}</p>
          </div>
          <div class="flex items-center gap-2">
            <select :value="s.permission" @change="setPermission(s, $event.target.value)" class="dh-input w-auto !py-1 !text-xs">
              <option value="read">{{ t("forms.share.read") }}</option>
              <option value="write">{{ t("forms.share.write") }}</option>
            </select>
            <button class="text-xs font-medium text-danger hover:underline" @click="removeShare(s)">{{ t("common.remove") }}</button>
          </div>
        </li>
      </ul>
    </div>

    <div class="mt-6 flex justify-end">
      <button type="button" class="dh-btn dh-btn-ghost" @click="emit('close')">{{ t("common.done") }}</button>
    </div>
  </Modal>
</template>
