<script setup>
import { ref, computed, onMounted } from "vue";
import { api } from "../api";
import { state, refreshProfile } from "../auth";
import { t } from "../i18n";
import { askConfirm } from "../lib/confirm.js";

// Organization management, adapting to who is looking:
//  - a user with no organization gets a "create your own" form, and becomes the
//    admin of what they create;
//  - an admin sees their own org with Rename + Delete (deleting it detaches them
//    and drops them back to a plain user);
//  - a superadmin sees every org and can create, rename and delete any of them.
// The API Server enforces all of this; this component only mirrors it.
const role = computed(() => state.profile?.role || state.user?.role || "user");
const isSuperadmin = computed(() => role.value === "superadmin");
const isManager = computed(() => ["admin", "superadmin"].includes(role.value));
const myOrg = computed(() => state.profile?.organization || "");
// Anyone who is not a superadmin and has no org yet can stand one up.
const showCreateOwn = computed(() => !isSuperadmin.value && !myOrg.value);

const orgs = ref([]);
const error = ref("");
const busy = ref(false);
const editing = ref(null); // org id, or "new"
const draftName = ref("");
const createName = ref(""); // for the org-less "create your own" form

async function load() {
  // Listing is manager-only; an org-less user just gets the create form.
  if (!isManager.value) {
    orgs.value = [];
    return;
  }
  try {
    orgs.value = (await api.listOrgs()) || [];
    error.value = "";
  } catch (e) {
    error.value = e.message;
  }
}
onMounted(load);

// An org-less user creates their first org and is promoted to its admin.
async function createOwnOrg() {
  const name = createName.value.trim();
  if (!name) return;
  busy.value = true;
  error.value = "";
  try {
    await api.createOrg(name);
    createName.value = "";
    await refreshProfile(); // role -> admin, organization now set
    await load();
  } catch (e) {
    error.value = e.message;
  } finally {
    busy.value = false;
  }
}

function startNew() {
  editing.value = "new";
  draftName.value = "";
}
function startEdit(o) {
  editing.value = o.id;
  draftName.value = o.name;
}
function cancel() {
  editing.value = null;
  error.value = "";
}

async function save() {
  const name = draftName.value.trim();
  if (!name) return;
  busy.value = true;
  error.value = "";
  try {
    if (editing.value === "new") {
      await api.createOrg(name);
      if (!isSuperadmin.value) await refreshProfile();
    } else {
      await api.updateOrg(editing.value, name);
    }
    editing.value = null;
    await load();
  } catch (e) {
    error.value = e.message;
  } finally {
    busy.value = false;
  }
}

async function remove(o) {
  const mine = !isSuperadmin.value && o.id === myOrg.value;
  const msg = mine
    ? t("settings.org.confirmDeleteOwn", { name: o.name })
    : t("settings.org.confirmDelete", { name: o.name });
  if (!(await askConfirm(msg))) return;
  busy.value = true;
  error.value = "";
  try {
    await api.deleteOrg(o.id);
    if (mine) await refreshProfile(); // now org-less and demoted to user
    await load();
  } catch (e) {
    // The server refuses (409) while the org still has other members.
    error.value = e.message;
  } finally {
    busy.value = false;
  }
}
</script>

<template>
  <section class="dh-card p-6">
    <div class="mb-4 flex items-center justify-between gap-3">
      <div>
        <h2 class="text-lg font-bold tracking-[-0.02em] text-strong">
          {{ isSuperadmin ? t("settings.org.titleAll") : t("settings.org.title") }}
        </h2>
        <p class="mt-0.5 text-xs text-muted">
          {{
            isSuperadmin
              ? t("settings.org.subtitleAll")
              : showCreateOwn
                ? t("settings.org.subtitleNone")
                : t("settings.org.subtitleOwn")
          }}
        </p>
      </div>
      <button v-if="isSuperadmin" class="dh-btn dh-btn-ghost !px-3 !py-1.5 shrink-0" @click="startNew">
        {{ t("settings.org.newOrg") }}
      </button>
    </div>

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

    <!-- Org-less user: create your own organization and become its admin -->
    <div v-if="showCreateOwn">
      <label class="dh-label">{{ t("settings.org.nameLabel") }}</label>
      <div class="flex flex-wrap items-center gap-2">
        <input
          v-model="createName"
          class="dh-input max-w-sm"
          :placeholder="t('settings.org.namePlaceholder')"
          autocomplete="off"
          @keyup.enter="createOwnOrg"
        />
        <button class="dh-btn shrink-0" :disabled="busy || !createName.trim()" @click="createOwnOrg">
          {{ t("settings.org.create") }}
        </button>
      </div>
      <p class="mt-2 text-xs text-muted">{{ t("settings.org.createHint") }}</p>
    </div>

    <!-- Managers: manage the organization(s) they own -->
    <template v-else>
      <div v-if="editing" class="mb-4 rounded-control bg-sunken p-4">
        <label class="dh-label">{{ t("settings.org.nameLabel") }}</label>
        <input
          v-model="draftName"
          class="dh-input max-w-sm"
          :placeholder="t('settings.org.namePlaceholder')"
          autocomplete="off"
          @keyup.enter="save"
        />
        <div class="mt-3 flex items-center gap-2">
          <button class="dh-btn" :disabled="busy || !draftName.trim()" @click="save">
            {{ editing === "new" ? t("settings.org.create") : t("common.save") }}
          </button>
          <button class="dh-btn dh-btn-ghost" :disabled="busy" @click="cancel">{{ t("common.cancel") }}</button>
        </div>
      </div>

      <p v-if="!orgs.length" class="text-sm text-muted">{{ t("settings.org.empty") }}</p>

      <ul v-else class="divide-y divide-subtle">
        <li v-for="o in orgs" :key="o.id" class="flex items-center justify-between gap-3 py-3 first:pt-0 last:pb-0">
          <div class="min-w-0">
            <p class="truncate text-sm font-medium text-strong">{{ o.name }}</p>
            <p class="data truncate text-xs text-muted">{{ o.id }}</p>
          </div>
          <div class="flex shrink-0 items-center gap-2">
            <button class="dh-btn dh-btn-ghost !px-3 !py-1.5" @click="startEdit(o)">
              {{ t("settings.org.rename") }}
            </button>
            <button
              class="dh-btn dh-btn-ghost !px-3 !py-1.5 !text-danger"
              :disabled="busy"
              @click="remove(o)"
            >
              {{ t("common.delete") }}
            </button>
          </div>
        </li>
      </ul>
    </template>
  </section>
</template>
