<template>
  <main class="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 p-6">
    <div class="max-w-4xl mx-auto">
      <div class="flex items-center justify-between mb-6">
        <div>
          <h1 class="text-2xl font-bold">
            Gestion des profils
          </h1>
          <p class="text-sm text-base-content/70">
            Sélectionnez, créez ou supprimez des profils.
          </p>
        </div>
        <NuxtLink to="/" class="btn btn-ghost btn-sm">
          Retour
        </NuxtLink>
      </div>

      <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <section class="card bg-base-100 shadow-lg">
          <div class="card-body space-y-4">
            <header class="flex items-center justify-between">
              <h2 class="card-title text-lg">
                Profils existants
              </h2>
              <button type="button" class="btn btn-ghost btn-xs" :disabled="loadingProfiles" @click="refresh">
                <span v-if="loadingProfiles" class="loading loading-spinner loading-xs" />
                <span v-else>Rafraîchir</span>
              </button>
            </header>

            <div v-if="profiles.length" class="space-y-2 max-h-80 overflow-y-auto">
              <div
                v-for="profile in profiles"
                :key="profile.id"
                class="flex items-center justify-between rounded-lg border border-base-200 bg-base-100 px-3 py-2"
              >
                <div>
                  <p class="font-medium">
                    {{ profile.firstName }} {{ profile.lastName }}
                  </p>
                  <p class="text-xs text-base-content/60">
                    ID : {{ profile.id }}
                  </p>
                </div>
                <div class="flex items-center gap-2">
                  <button
                    type="button"
                    class="btn btn-sm"
                    :class="profile.id === activeProfile?.id ? 'btn-primary' : 'btn-outline'"
                    @click="select(profile.id)"
                  >
                    {{ profile.id === activeProfile?.id ? 'Actif' : 'Activer' }}
                  </button>
                  <button
                    type="button"
                    class="btn btn-error btn-sm"
                    @click="remove(profile.id)"
                  >
                    <span v-if="deleting === profile.id" class="loading loading-spinner loading-xs" />
                    <span v-else>Supprimer</span>
                  </button>
                </div>
              </div>
            </div>
            <p v-else class="text-sm text-base-content/60">
              Aucun profil enregistré.
            </p>
          </div>
        </section>

        <section class="card bg-base-100 shadow-lg">
          <div class="card-body space-y-4">
            <h2 class="card-title text-lg">
              Créer un profil
            </h2>
            <form class="space-y-3" @submit.prevent="create">
              <div class="form-control">
                <label class="label"><span class="label-text">Prénom</span></label>
                <input
                  v-model="createForm.firstName"
                  type="text"
                  class="input input-bordered"
                  placeholder="Prénom"
                  required
                >
              </div>
              <div class="form-control">
                <label class="label"><span class="label-text">Nom</span></label>
                <input
                  v-model="createForm.lastName"
                  type="text"
                  class="input input-bordered"
                  placeholder="Nom"
                  required
                >
              </div>
              <button type="submit" class="btn btn-primary w-full" :disabled="creating">
                <span v-if="creating" class="loading loading-spinner loading-sm" />
                <span v-else>Créer et activer</span>
              </button>
            </form>
          </div>
        </section>
      </div>

      <div v-if="activeProfile" class="mt-8 flex items-center justify-between bg-base-100 shadow-lg rounded-lg p-4">
        <div>
          <p class="text-sm text-base-content/70">
            Profil actif :
          </p>
          <p class="font-semibold text-base-content">
            {{ activeProfile.firstName }} {{ activeProfile.lastName }}
          </p>
        </div>
        <button type="button" class="btn btn-outline" @click="handleLogout">
          Déconnexion
        </button>
      </div>
    </div>
  </main>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useProfiles, useProfileSession } from '#imports'

const router = useRouter()
const { profiles, loadingProfiles, fetchProfiles, createProfile, deleteProfile } = useProfiles()
const { activeProfile, activateProfile, fetchCurrentProfile, logout } = useProfileSession()

const createForm = reactive({
  firstName: '',
  lastName: ''
})

const creating = ref(false)
const deleting = ref(null)

const refresh = async () => {
  await fetchProfiles()
  await fetchCurrentProfile()
}

const select = async (profileId) => {
  try {
    await activateProfile(profileId)
    await refresh()
  } catch (error) {
    console.error('Erreur lors de la sélection du profil', error)
  }
}

const create = async () => {
  creating.value = true
  try {
    const profile = await createProfile({
      firstName: createForm.firstName,
      lastName: createForm.lastName
    })
    createForm.firstName = ''
    createForm.lastName = ''
    await activateProfile(profile.id)
    await refresh()
  } catch (error) {
    console.error('Erreur lors de la création du profil', error)
  } finally {
    creating.value = false
  }
}

const remove = async (profileId) => {
  if (!confirm('Supprimer ce profil ?')) { return }
  deleting.value = profileId
  try {
    await deleteProfile(profileId)
    await refresh()
  } catch (error) {
    console.error('Erreur lors de la suppression du profil', error)
  } finally {
    deleting.value = null
  }
}

const handleLogout = async () => {
  await logout()
  await refresh()
  await router.push('/profiles')
}

onMounted(async () => {
  await refresh()
})
</script>
