<template>
  <div v-if="user" class="cata-user-info">
    <div class="cata-outline-box rounded-lg p-4">
      <div class="flex items-center gap-3">
        <!-- Avatar clickeable para verificar sesión -->
        <button
          class="user-avatar cata-outline-box cursor-pointer"
          @click="handleCheckSession"
          title="Verificar estado de sesión"
        >
          <span class="cata-text text-xl font-semibold">
            {{ userInitial }}
          </span>
        </button>

        <!-- Info del usuario -->
        <div class="flex-1 min-w-0">
          <h3 class="cata-text font-semibold text-base sm:text-lg truncate">
            {{ user.name || user.username }}
          </h3>
          <p class="cata-text text-xs sm:text-sm opacity-60 truncate">
            {{ user.email }}
          </p>
        </div>

        <!-- Botones de acción -->
        <div class="flex items-center gap-2">
          <!-- Modal de personalización de color -->
          <UModal v-model:open="mostrarColorPicker" title="Personalizar Color del Tema" :description="`Selecciona un color para el tema ${isDark ? 'oscuro' : 'claro'}`">
            <!-- Trigger button -->
            <button
              class="cata-button p-2 flex items-center justify-center flex-shrink-0"
              title="Personalizar color del tema"
            >
              <UIcon name="i-lucide-palette" class="w-4 h-4" />
            </button>

            <!-- Modal body -->
            <template #body>
              <!-- Color Principal -->
              <div class="mb-4">
                <label class="cata-text text-sm font-medium mb-2 block">
                  Color Principal
                </label>
                <div class="flex items-center gap-3">
                  <input
                    type="color"
                    v-model="colorPrimario"
                    class="color-picker"
                  />
                  <input
                    type="text"
                    v-model="colorPrimario"
                    class="cata-input flex-1 px-3 py-2 rounded-md"
                    placeholder="#4682B4"
                    maxlength="7"
                    pattern="^#[0-9A-Fa-f]{6}$"
                  />
                </div>
              </div>

              <!-- Color de Fuente -->
              <div class="mb-4">
                <label class="cata-text text-sm font-medium mb-2 block">
                  Color de Fuente
                </label>
                <div class="flex items-center gap-3">
                  <input
                    type="color"
                    v-model="colorFuente"
                    class="color-picker"
                  />
                  <input
                    type="text"
                    v-model="colorFuente"
                    class="cata-input flex-1 px-3 py-2 rounded-md"
                    placeholder="#000000"
                    maxlength="7"
                    pattern="^#[0-9A-Fa-f]{6}$"
                  />
                </div>
              </div>

              <!-- Color de Fondo -->
              <div class="mb-6">
                <label class="cata-text text-sm font-medium mb-2 block">
                  Color de Fondo
                </label>
                <div class="flex items-center gap-3">
                  <input
                    type="color"
                    v-model="colorFondo"
                    class="color-picker"
                  />
                  <input
                    type="text"
                    v-model="colorFondo"
                    class="cata-input flex-1 px-3 py-2 rounded-md"
                    placeholder="#ffffff"
                    maxlength="7"
                    pattern="^#[0-9A-Fa-f]{6}$"
                  />
                </div>
              </div>

              <!-- Vista previa -->
              <div class="mb-6">
                <p class="cata-text text-sm font-medium mb-2">
                  Vista previa
                </p>
                <div
                  class="preview-box cata-outline-box rounded-md p-4"
                  :style="{
                    backgroundColor: colorFondo,
                    borderColor: colorPrimario
                  }"
                >
                  <p
                    class="text-sm mb-2"
                    :style="{ color: colorFuente }"
                  >
                    Texto de ejemplo
                  </p>
                  <button
                    class="cata-button px-4 py-2"
                    :style="{
                      borderColor: colorPrimario,
                      color: colorPrimario
                    }"
                  >
                    Botón de ejemplo
                  </button>
                </div>
              </div>
            </template>

            <!-- Modal footer -->
            <template #footer>
              <div class="flex items-center justify-end gap-2 w-full">
                <button
                  v-if="hasCustomColors"
                  class="cata-button px-4 py-2"
                  @click="resetearColores"
                >
                  Restablecer
                </button>
                <button
                  class="cata-button px-4 py-2"
                  @click="mostrarColorPicker = false"
                >
                  Cancelar
                </button>
                <button
                  class="cata-button px-4 py-2"
                  @click="aplicarColores"
                >
                  Aplicar
                </button>
              </div>
            </template>
          </UModal>

          <!-- Botón de cambio de tema -->
          <button
            class="cata-button p-2 flex items-center justify-center flex-shrink-0"
            @click="toggleTheme"
            :title="isDark ? 'Cambiar a modo claro' : 'Cambiar a modo oscuro'"
          >
            <UIcon :name="isDark ? 'i-lucide-sun' : 'i-lucide-moon'" class="w-4 h-4" />
          </button>

          <!-- Botón de home -->
          <button
            class="cata-button p-2 flex items-center justify-center flex-shrink-0"
            @click="goToHome"
            title="Ir al inicio del ecosistema Nucleo"
          >
            <UIcon name="i-lucide-home" class="w-4 h-4" />
          </button>

          <!-- Botón de logout -->
          <button
            class="cata-button p-2 flex items-center justify-center flex-shrink-0"
            @click="handleLogout"
            title="Cerrar sesión"
          >
            <UIcon name="i-lucide-log-out" class="w-4 h-4" />
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
const { user, checkSessionStatus } = useAuthentik()
const colorMode = useColorMode()
const { getCurrentColors, hasCustomColors, setCustomColors, resetColors } = useColorCustomization()

// Estado del tema
const isDark = computed(() => colorMode.value === 'dark')

// Estado del modal de color picker
const mostrarColorPicker = ref(false)
const colorPrimario = ref(getCurrentColors.value.primary)
const colorFuente = ref(getCurrentColors.value.foreground)
const colorFondo = ref(getCurrentColors.value.background)

// Actualizar colores seleccionados cuando cambia el tema
watch(getCurrentColors, (newColors) => {
  colorPrimario.value = newColors.primary
  colorFuente.value = newColors.foreground
  colorFondo.value = newColors.background
})

// Obtener la inicial del usuario
const userInitial = computed(() => {
  if (!user.value) return '?'
  const name = user.value.name || user.value.username || user.value.email || '?'
  return name.charAt(0).toUpperCase()
})

// Cambiar tema
const toggleTheme = () => {
  colorMode.preference = isDark.value ? 'light' : 'dark'
}

// Ir al home del ecosistema
const goToHome = () => {
  window.open('https://inicio.nucleoriofrio.com', '_blank')
}

// Verificar estado de sesión
const handleCheckSession = async () => {
  await checkSessionStatus()
}

// Manejar logout
const handleLogout = () => {
  // Redirigir al endpoint de logout de Authentik
  window.location.href = '/outpost.goauthentik.io/sign_out'
}

// Aplicar colores personalizados
const aplicarColores = () => {
  setCustomColors(colorPrimario.value, colorFuente.value, colorFondo.value)
  mostrarColorPicker.value = false
}

// Resetear colores a los por defecto
const resetearColores = () => {
  resetColors()
  const colors = getCurrentColors.value
  colorPrimario.value = colors.primary
  colorFuente.value = colors.foreground
  colorFondo.value = colors.background
}
</script>

<style scoped>
.cata-user-info {
  width: 100%;
}

.user-avatar {
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  background-color: color-mix(in srgb, var(--cata-primary) 5%, transparent);
  border: none;
}

.dark .user-avatar {
  background-color: color-mix(in srgb, var(--cata-primary) 10%, transparent);
  box-shadow: 0 0 8px color-mix(in srgb, var(--cata-primary) 20%, transparent);
}

.user-avatar:hover {
  background-color: color-mix(in srgb, var(--cata-primary) 10%, transparent);
}

.dark .user-avatar:hover {
  background-color: color-mix(in srgb, var(--cata-primary) 15%, transparent);
  box-shadow: 0 0 12px color-mix(in srgb, var(--cata-primary) 30%, transparent);
}

/* Color picker */
.color-picker {
  width: 3rem;
  height: 3rem;
  border: 2px solid color-mix(in srgb, var(--cata-primary) 50%, transparent);
  border-radius: 0.375rem;
  cursor: pointer;
  background-color: transparent;
  transition: border-color 200ms;
}

.color-picker:hover {
  border-color: color-mix(in srgb, var(--cata-primary) 70%, transparent);
}

.dark .color-picker {
  border-color: var(--cata-primary);
}

.dark .color-picker:hover {
  box-shadow: 0 0 8px color-mix(in srgb, var(--cata-primary) 30%, transparent);
}

/* Input de texto para color */
.cata-input {
  background-color: transparent;
  border: 2px solid color-mix(in srgb, var(--cata-primary) 30%, transparent);
  color: var(--cata-fg);
  transition: border-color 200ms, box-shadow 200ms;
}

.cata-input:focus {
  outline: none;
  border-color: color-mix(in srgb, var(--cata-primary) 70%, transparent);
}

.dark .cata-input {
  border-color: color-mix(in srgb, var(--cata-primary) 50%, transparent);
  font-family: 'Roboto Mono', monospace;
}

.dark .cata-input:focus {
  border-color: var(--cata-primary);
  box-shadow: 0 0 8px color-mix(in srgb, var(--cata-primary) 20%, transparent);
}

/* Preview box */
.preview-box {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 4rem;
  background-color: color-mix(in srgb, var(--cata-primary) 2%, transparent);
}

.dark .preview-box {
  background-color: color-mix(in srgb, var(--cata-primary) 5%, transparent);
}

/* Responsive adjustments */
@media (max-width: 640px) {
  .user-avatar {
    width: 2rem;
    height: 2rem;
  }

  .user-avatar .cata-text {
    font-size: 1rem;
  }
}
</style>
