<script setup>
import { ref, onMounted, computed } from "vue";
import { request, me, isSuperadmin } from "../api";
import { t } from "../i18n";

// Manager-only. A superadmin sees and edits everyone; an admin is scoped by the
// server to their own organization. The UI mirrors those limits, but the server
// is what enforces them.
const users = ref([]);
const orgs = ref([]);
const error = ref("");
const busy = ref(false);
const editing = ref(null); // user id being edited, or "new"
const draft = ref({});

const roles = computed(() =>
  isSuperadmin.value ? ["user", "admin", "superadmin"] : ["user", "admin"],
);

async function load() {
  try {
    const [u, o] = await Promise.all([request("/api/users"), request("/api/orgs")]);
    users.value = u.users || [];
    orgs.value = o.organizations || [];
    error.value = "";
  } catch (e) {
    error.value = e.message;
  }
}
onMounted(load);

function startNew() {
  editing.value = "new";
  draft.value = {
    email: "",
    name: "",
    password: "",
    role: "user",
    organization: isSuperadmin.value ? "" : me.value?.organization || "",
  };
}

function startEdit(u) {
  editing.value = u.id;
  draft.value = {
    email: u.email,
    name: u.name || "",
    password: "",
    role: u.role,
    organization: u.organization || "",
  };
}

function cancel() {
  editing.value = null;
  error.value = "";
}

async function save() {
  busy.value = true;
  error.value = "";
  try {
    if (editing.value === "new") {
      await request("/api/users", { method: "POST", body: draft.value });
    } else {
      // Only send a password when one was typed — blank means "leave it".
      const body = { ...draft.value };
      if (!body.password) delete body.password;
      await request(`/api/users/${editing.value}`, { method: "PATCH", body });
    }
    editing.value = null;
    await load();
  } catch (e) {
    error.value = e.message;
  } finally {
    busy.value = false;
  }
}

async function remove(u) {
  if (!confirm(t("users.confirmDelete", { email: u.email }))) return;
  busy.value = true;
  error.value = "";
  try {
    await request(`/api/users/${u.id}`, { method: "DELETE" });
    await load();
  } catch (e) {
    error.value = e.message;
  } finally {
    busy.value = false;
  }
}

const roleClass = (r) =>
  r === "superadmin"
    ? "bg-info-soft text-info"
    : r === "admin"
      ? "bg-warning-soft text-warning"
      : "bg-sunken text-muted";
</script>

<template>
  <div class="dh-card overflow-hidden">
    <div class="flex items-center justify-between border-b border-subtle px-5 py-4">
      <div>
        <div class="text-base font-bold tracking-[-0.02em] text-strong">{{ t("users.title") }}</div>
        <p class="mt-0.5 text-xs text-muted">
          {{ isSuperadmin ? t("users.allOrgs") : t("users.yourOrg") }}
        </p>
      </div>
      <button class="dh-btn" @click="startNew">{{ t("users.newUser") }}</button>
    </div>

    <p v-if="error" class="border-b border-subtle px-5 py-3 text-xs text-danger">{{ error }}</p>

    <!-- Create / edit form -->
    <div v-if="editing" class="border-b border-subtle bg-sunken px-5 py-4">
      <div class="grid gap-3 sm:grid-cols-2">
        <div>
          <label class="dh-label">{{ t("common.email") }}</label>
          <input v-model="draft.email" class="dh-input" type="email" autocomplete="off" />
        </div>
        <div>
          <label class="dh-label">{{ t("common.name") }}</label>
          <input v-model="draft.name" class="dh-input" autocomplete="off" />
        </div>
        <div>
          <label class="dh-label">
            {{ editing === "new" ? t("users.password") : t("users.passwordUnchanged") }}
          </label>
          <input
            v-model="draft.password"
            class="dh-input"
            type="password"
            autocomplete="new-password"
            :placeholder="t('users.passwordPlaceholder')"
          />
        </div>
        <div>
          <label class="dh-label">{{ t("common.role") }}</label>
          <select v-model="draft.role" class="dh-select">
            <option v-for="r in roles" :key="r" :value="r">{{ r }}</option>
          </select>
        </div>
        <div v-if="isSuperadmin">
          <label class="dh-label">{{ t("common.organization") }}</label>
          <select v-model="draft.organization" class="dh-select">
            <option value="">{{ t("users.orgNone") }}</option>
            <option v-for="o in orgs" :key="o.id" :value="o.id">{{ o.name }}</option>
          </select>
        </div>
      </div>
      <div class="mt-3 flex items-center gap-2">
        <button class="dh-btn" :disabled="busy" @click="save">
          {{ editing === "new" ? t("common.create") : t("common.save") }}
        </button>
        <button class="dh-btn-ghost" :disabled="busy" @click="cancel">{{ t("common.cancel") }}</button>
      </div>
    </div>

    <p v-if="!users.length" class="px-5 py-6 text-center text-sm text-muted">{{ t("users.empty") }}</p>

    <table v-else class="w-full text-left text-sm">
      <thead>
        <tr class="[&>th]:eyebrow [&>th]:px-5 [&>th]:py-2.5 [&>th]:font-medium">
          <th>{{ t("common.email") }}</th>
          <th>{{ t("common.name") }}</th>
          <th>{{ t("common.organization") }}</th>
          <th>{{ t("common.role") }}</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="u in users" :key="u.id" class="border-t border-subtle transition-colors hover:bg-sunken">
          <td class="data px-5 py-2.5 text-xs text-strong">
            {{ u.email }}
            <span v-if="u.id === me?.id" class="eyebrow ml-1">{{ t("users.you") }}</span>
          </td>
          <td class="px-5 py-2.5 text-body">{{ u.name || t("common.empty") }}</td>
          <td class="px-5 py-2.5 text-body">{{ u.organizationName || t("common.empty") }}</td>
          <td class="px-5 py-2.5">
            <span class="dh-pill" :class="roleClass(u.role)">{{ u.role }}</span>
          </td>
          <td class="px-5 py-2.5 text-right whitespace-nowrap">
            <button class="dh-btn-ghost" @click="startEdit(u)">{{ t("common.edit") }}</button>
            <button
              v-if="u.id !== me?.id"
              class="dh-btn-danger ml-1.5"
              :disabled="busy"
              @click="remove(u)"
            >
              {{ t("common.delete") }}
            </button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>
