<template>
  <div class="profile-form-container">
    <div class="form-header">
      <div class="flex items-center justify-between mb-4">
        <h2 class="form-title">
          <UIcon name="i-heroicons-user-circle" class="w-6 h-6" />
          Editar Perfil
        </h2>
        <UButton
          color="neutral"
          variant="ghost"
          icon="i-heroicons-x-mark"
          @click="$emit('close')"
        >
          Cancelar
        </UButton>
      </div>
    </div>

    <form @submit.prevent="handleSubmit" class="form-content">
      <div class="form-grid">
        <!-- Nombre de usuario (readonly) -->
        <UFormGroup label="Nombre de usuario" name="username">
          <UInput
            :model-value="user?.username"
            disabled
            :ui="{ base: 'cursor-not-allowed opacity-50' }"
          />
          <template #help>
            <span class="text-xs text-gray-500">El nombre de usuario no se puede cambiar</span>
          </template>
        </UFormGroup>

        <!-- Nombre completo -->
        <UFormGroup label="Nombre completo" name="name" required>
          <UInput
            v-model="formData.name"
            placeholder="Tu nombre completo"
            :disabled="isSubmitting"
          />
        </UFormGroup>

        <!-- Email -->
        <UFormGroup label="Correo electrónico" name="email" required>
          <UInput
            v-model="formData.email"
            type="email"
            placeholder="tu@email.com"
            :disabled="isSubmitting"
          />
        </UFormGroup>

        <!-- Avatar URL (deshabilitado) -->
        <UFormGroup label="URL del avatar" name="avatar">
          <UInput
            v-model="formData.avatar"
            placeholder="https://ejemplo.com/avatar.jpg"
            disabled
            :ui="{ base: 'cursor-not-allowed opacity-50' }"
          />
          <template #help>
            <span class="text-xs text-gray-500">Próximamente disponible</span>
          </template>
        </UFormGroup>

        <!-- Teléfono (deshabilitado) -->
        <UFormGroup label="Teléfono" name="phone">
          <UInput
            v-model="formData.phone"
            placeholder="+506 1234-5678"
            disabled
            :ui="{ base: 'cursor-not-allowed opacity-50' }"
          />
          <template #help>
            <span class="text-xs text-gray-500">Próximamente disponible</span>
          </template>
        </UFormGroup>

        <!-- Cédula (deshabilitado) -->
        <UFormGroup label="Cédula" name="cedula">
          <UInput
            v-model="formData.cedula"
            placeholder="1-2345-6789"
            disabled
            :ui="{ base: 'cursor-not-allowed opacity-50' }"
          />
          <template #help>
            <span class="text-xs text-gray-500">Próximamente disponible</span>
          </template>
        </UFormGroup>

        <!-- Fecha de nacimiento (deshabilitado) -->
        <UFormGroup label="Fecha de nacimiento" name="birthdate">
          <UInput
            v-model="formData.birthdate"
            type="date"
            disabled
            :ui="{ base: 'cursor-not-allowed opacity-50' }"
          />
          <template #help>
            <span class="text-xs text-gray-500">Próximamente disponible</span>
          </template>
        </UFormGroup>

        <!-- NFC vinculada (deshabilitado) -->
        <UFormGroup label="NFC vinculada" name="nfc">
          <UInput
            v-model="formData.nfc"
            placeholder="ID de tarjeta NFC"
            disabled
            :ui="{ base: 'cursor-not-allowed opacity-50' }"
          />
          <template #help>
            <span class="text-xs text-gray-500">Próximamente disponible</span>
          </template>
        </UFormGroup>

        <!-- PIN numérico (deshabilitado) -->
        <UFormGroup label="PIN numérico" name="pin">
          <UInput
            v-model="formData.pin"
            type="password"
            placeholder="••••"
            disabled
            :ui="{ base: 'cursor-not-allowed opacity-50' }"
          />
          <template #help>
            <span class="text-xs text-gray-500">Próximamente disponible</span>
          </template>
        </UFormGroup>

        <!-- Código Nucleo V2 (deshabilitado) -->
        <UFormGroup label="Código Nucleo V2" name="nucleoCode">
          <UInput
            v-model="formData.nucleoCode"
            placeholder="NUCLEO-XXXX-XXXX"
            disabled
            :ui="{ base: 'cursor-not-allowed opacity-50' }"
          />
          <template #help>
            <span class="text-xs text-gray-500">Próximamente disponible</span>
          </template>
        </UFormGroup>
      </div>

      <!-- Botones de acción -->
      <div class="form-actions">
        <UButton
          color="neutral"
          variant="ghost"
          size="lg"
          @click="$emit('close')"
          :disabled="isSubmitting"
        >
          Cancelar
        </UButton>
        <UButton
          color="primary"
          size="lg"
          type="submit"
          :loading="isSubmitting"
        >
          Guardar cambios
        </UButton>
      </div>
    </form>
  </div>
</template>

<script setup lang="ts">
const { user } = useAuthentik()
const toast = useToast()

// Emits
defineEmits(['close'])

// Estado del formulario
const isSubmitting = ref(false)

// Datos del formulario
const formData = ref({
  name: user.value?.name || '',
  email: user.value?.email || '',
  avatar: '',
  phone: '',
  cedula: '',
  birthdate: '',
  nfc: '',
  pin: '',
  nucleoCode: ''
})

// Enviar formulario
const handleSubmit = async () => {
  if (!formData.value.name || !formData.value.email) {
    toast.add({
      title: 'Error',
      description: 'Por favor completa todos los campos requeridos',
      color: 'error',
      icon: 'i-heroicons-exclamation-triangle'
    })
    return
  }

  isSubmitting.value = true

  try {
    await $fetch('/api/authentik/user', {
      method: 'PATCH',
      body: {
        name: formData.value.name,
        email: formData.value.email
      }
    })

    toast.add({
      title: 'Perfil actualizado',
      description: 'Tus cambios se guardaron correctamente. Recarga la página para verlos.',
      color: 'success',
      icon: 'i-heroicons-check-circle',
      actions: [{
        label: 'Recargar',
        onClick: () => window.location.reload()
      }]
    })
  } catch (error) {
    console.error('Error updating profile:', error)
    toast.add({
      title: 'Error',
      description: 'No se pudo actualizar el perfil',
      color: 'error',
      icon: 'i-heroicons-x-circle'
    })
  } finally {
    isSubmitting.value = false
  }
}
</script>

<style scoped>
.profile-form-container {
  background: rgba(255, 255, 255, 0.35);
  backdrop-filter: blur(20px) saturate(180%);
  border-radius: 1.5rem;
  padding: 2rem;
  box-shadow:
    0 8px 32px 0 rgba(31, 38, 135, 0.15),
    inset 0 1px 1px 0 rgba(255, 255, 255, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.18);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.form-header {
  margin-bottom: 2rem;
}

.form-title {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  font-size: 1.75rem;
  font-weight: 700;
  color: var(--color-gray-900);
  margin: 0;
}

.form-content {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1.5rem;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  padding-top: 1rem;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}

/* Responsive */
@media (max-width: 768px) {
  .profile-form-container {
    padding: 1.5rem;
  }

  .form-title {
    font-size: 1.5rem;
  }

  .form-grid {
    grid-template-columns: 1fr;
    gap: 1rem;
  }

  .form-actions {
    flex-direction: column;
  }
}
</style>

<style>
/* Estilos de modo oscuro (sin scoped para que .dark funcione correctamente) */
.dark .profile-form-container {
  background: rgba(0, 0, 0, 0.15) !important;
  box-shadow:
    0 8px 32px 0 rgba(0, 0, 0, 0.5),
    inset 0 1px 1px 0 rgba(255, 255, 255, 0.05) !important;
  border: 1px solid rgba(255, 255, 255, 0.08) !important;
}

.dark .form-title {
  color: var(--color-gray-100) !important;
}

.dark .form-actions {
  border-top-color: rgba(255, 255, 255, 0.1);
}
</style>
