<script setup>
import { ref, onMounted } from "vue";
import { UserPlus, Trash2, KeyRound, Users } from "lucide-vue-next";
import { useAuthStore } from "../stores/auth";

const auth = useAuthStore();

const users = ref([]);
const loading = ref(false);
const error = ref("");

// New user form
const newUsername = ref("");
const newPassword = ref("");
const newRole = ref("admin");
const addError = ref("");
const addLoading = ref(false);

// Change password
const changingId = ref(null);
const newPwd = ref("");
const pwdError = ref("");

async function authFetch(url, options = {}) {
  const headers = { "Content-Type": "application/json" };
  if (auth.token) headers["Authorization"] = `Bearer ${auth.token}`;
  return fetch(url, { headers, ...options });
}

async function loadUsers() {
  loading.value = true;
  error.value = "";
  try {
    const res = await authFetch("/api/users");
    users.value = await res.json();
  } catch {
    error.value = "Error al cargar usuarios";
  } finally {
    loading.value = false;
  }
}

async function addUser() {
  addError.value = "";
  addLoading.value = true;
  try {
    const res = await authFetch("/api/users", {
      method: "POST",
      body: JSON.stringify({
        username: newUsername.value,
        password: newPassword.value,
        role: newRole.value,
      }),
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.error);
    newUsername.value = "";
    newPassword.value = "";
    await loadUsers();
  } catch (e) {
    addError.value = e.message;
  } finally {
    addLoading.value = false;
  }
}

async function deleteUser(id) {
  if (!confirm("¿Eliminar este usuario?")) return;
  await authFetch(`/api/users/${id}`, { method: "DELETE" });
  await loadUsers();
}

async function changePassword(id) {
  pwdError.value = "";
  try {
    const res = await authFetch(`/api/users/${id}/password`, {
      method: "PUT",
      body: JSON.stringify({ password: newPwd.value }),
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.error);
    changingId.value = null;
    newPwd.value = "";
  } catch (e) {
    pwdError.value = e.message;
  }
}

onMounted(loadUsers);
</script>

<template>
  <div class="space-y-8">
    <!-- User list -->
    <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
      <div class="flex items-center gap-2 mb-6">
        <Users class="w-5 h-5 text-blue-900" />
        <h3 class="text-lg font-bold text-blue-900">Utilisateurs</h3>
      </div>

      <p v-if="loading" class="text-gray-400 text-sm">Chargement…</p>
      <p v-else-if="error" class="text-red-500 text-sm">{{ error }}</p>

      <table v-else class="w-full text-sm">
        <thead>
          <tr class="text-left text-gray-500 border-b">
            <th class="pb-2 font-semibold">Utilisateur</th>
            <th class="pb-2 font-semibold">Rôle</th>
            <th class="pb-2 font-semibold">Créé le</th>
            <th class="pb-2"></th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="u in users"
            :key="u.id"
            class="border-b last:border-0 hover:bg-gray-50"
          >
            <td class="py-3 font-medium capitalize">{{ u.username }}</td>
            <td class="py-3">
              <span
                class="bg-blue-100 text-blue-800 text-xs px-2 py-0.5 rounded-full"
              >
                {{ u.role }}
              </span>
            </td>
            <td class="py-3 text-gray-400">{{ u.createdAt?.slice(0, 10) }}</td>
            <td class="py-3">
              <div class="flex items-center gap-2 justify-end">
                <!-- Change password inline -->
                <template v-if="changingId === u.id">
                  <input
                    v-model="newPwd"
                    type="password"
                    placeholder="Nouveau mot de passe"
                    class="border rounded-lg px-2 py-1 text-xs w-44 focus:outline-none focus:ring-2 focus:ring-blue-400"
                  />
                  <button
                    @click="changePassword(u.id)"
                    class="text-xs bg-blue-900 text-white px-2 py-1 rounded-lg hover:bg-blue-800"
                  >
                    OK
                  </button>
                  <button
                    @click="
                      changingId = null;
                      newPwd = '';
                    "
                    class="text-xs text-gray-500 hover:text-gray-700"
                  >
                    ✕
                  </button>
                  <p v-if="pwdError" class="text-red-500 text-xs">
                    {{ pwdError }}
                  </p>
                </template>
                <template v-else>
                  <button
                    @click="changingId = u.id"
                    class="text-gray-400 hover:text-blue-700 transition-colors"
                    title="Changer le mot de passe"
                  >
                    <KeyRound class="w-4 h-4" />
                  </button>
                  <button
                    @click="deleteUser(u.id)"
                    class="text-gray-400 hover:text-red-600 transition-colors"
                    title="Supprimer"
                  >
                    <Trash2 class="w-4 h-4" />
                  </button>
                </template>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- Add user -->
    <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
      <div class="flex items-center gap-2 mb-6">
        <UserPlus class="w-5 h-5 text-blue-900" />
        <h3 class="text-lg font-bold text-blue-900">Ajouter un utilisateur</h3>
      </div>

      <form @submit.prevent="addUser" class="flex flex-wrap gap-3 items-end">
        <div class="flex flex-col gap-1">
          <label class="text-xs font-semibold text-gray-600">Utilisateur</label>
          <input
            v-model="newUsername"
            type="text"
            required
            class="border rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400 w-40"
          />
        </div>
        <div class="flex flex-col gap-1">
          <label class="text-xs font-semibold text-gray-600"
            >Mot de passe</label
          >
          <input
            v-model="newPassword"
            type="password"
            required
            class="border rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400 w-40"
          />
        </div>
        <div class="flex flex-col gap-1">
          <label class="text-xs font-semibold text-gray-600">Rôle</label>
          <select
            v-model="newRole"
            class="border rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400"
          >
            <option value="admin">admin</option>
          </select>
        </div>
        <button
          type="submit"
          :disabled="addLoading"
          class="flex items-center gap-2 bg-blue-900 hover:bg-blue-800 disabled:opacity-60 text-white text-sm font-semibold px-4 py-2 rounded-xl transition-colors"
        >
          <UserPlus class="w-4 h-4" />
          {{ addLoading ? "Ajout…" : "Ajouter" }}
        </button>
        <p v-if="addError" class="text-red-500 text-sm w-full">
          {{ addError }}
        </p>
      </form>
    </div>
  </div>
</template>
