<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">
          <!-- Botón de personalización de color -->
          <button
            class="cata-button p-2 flex items-center justify-center flex-shrink-0"
            @click="mostrarColorPicker = true"
            title="Personalizar color del tema"
          >
            <UIcon name="i-lucide-palette" class="w-4 h-4" />
          </button>

          <!-- 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>

    <!-- Modal de personalización de color -->
    <UModal v-model:open="mostrarColorPicker">
      <div class="cata-outline-box rounded-lg p-6">
        <h3 class="cata-text text-lg font-semibold mb-4">
          Personalizar Color del Tema
        </h3>
        <p class="cata-text text-sm opacity-75 mb-4">
          Selecciona un color para el tema {{ isDark ? 'oscuro' : 'claro' }}
        </p>

        <!-- Color picker -->
        <div class="mb-6">
          <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="colorSeleccionado"
              class="color-picker"
              @change="previsualizarColor"
            />
            <input
              type="text"
              v-model="colorSeleccionado"
              class="cata-input flex-1 px-3 py-2 rounded-md"
              placeholder="#000000"
              maxlength="7"
              pattern="^#[0-9A-Fa-f]{6}$"
            />
          </div>
        </div>

        <!-- Vista previa del color -->
        <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">
            <button
              class="cata-button px-4 py-2"
              :style="{
                '--preview-color': colorSeleccionado,
                borderColor: colorSeleccionado,
                color: colorSeleccionado
              }"
            >
              Botón de ejemplo
            </button>
          </div>
        </div>

        <!-- Botones de acción -->
        <div class="flex items-center justify-end gap-2">
          <button
            v-if="hasCustomColor"
            class="cata-button px-4 py-2"
            @click="resetearColor"
          >
            Restablecer
          </button>
          <button
            class="cata-button px-4 py-2"
            @click="mostrarColorPicker = false"
          >
            Cancelar
          </button>
          <button
            class="cata-button px-4 py-2"
            @click="aplicarColor"
          >
            Aplicar
          </button>
        </div>
      </div>
    </UModal>
  </div>
</template>

<script setup lang="ts">
const { user, checkSessionStatus } = useAuthentik()
const colorMode = useColorMode()
const { getCurrentColor, hasCustomColor, setCustomColor, resetColor } = useColorCustomization()

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

// Estado del modal de color picker
const mostrarColorPicker = ref(false)
const colorSeleccionado = ref(getCurrentColor.value)

// Actualizar color seleccionado cuando cambia el tema
watch(getCurrentColor, (newColor) => {
  colorSeleccionado.value = newColor
})

// 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'
}

// Previsualizar color
const previsualizarColor = () => {
  // La vista previa se maneja con el binding :style en el template
}

// Aplicar color personalizado
const aplicarColor = () => {
  setCustomColor(colorSeleccionado.value)
  mostrarColorPicker.value = false
}

// Resetear color al por defecto
const resetearColor = () => {
  resetColor()
  colorSeleccionado.value = getCurrentColor.value
}
</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>
