<script lang="ts">
  import { onMount } from 'svelte';
  import { auth } from '$lib/stores/auth.js';
  import { toast } from '$lib/stores/toast.js';
  import { goto } from '$app/navigation';
  
  let currentPassword = '';
  let newPassword = '';
  let confirmPassword = '';
  let firstName = '';
  let lastName = '';
  let isUpdatingProfile = false;
  let isChangingPassword = false;
  let profileErrors: Record<string, string> = {};
  let passwordErrors: Record<string, string> = {};
  
  onMount(() => {
    // Redirect if not authenticated
    if (!$auth.isAuthenticated) {
      goto('/login');
      return;
    }
    
    // Initialize form with user data
    if ($auth.user) {
      firstName = $auth.user.first_name;
      lastName = $auth.user.last_name;
    }
  });
  
  function validateProfileForm() {
    profileErrors = {};
    
    if (!firstName.trim()) {
      profileErrors.firstName = 'El nombre es requerido';
    }
    
    if (!lastName.trim()) {
      profileErrors.lastName = 'El apellido es requerido';
    }
    
    return Object.keys(profileErrors).length === 0;
  }
  
  function validatePasswordForm() {
    passwordErrors = {};
    
    if (!currentPassword) {
      passwordErrors.currentPassword = 'La contraseña actual es requerida';
    }
    
    if (!newPassword) {
      passwordErrors.newPassword = 'La nueva contraseña es requerida';
    } else if (newPassword.length < 8) {
      passwordErrors.newPassword = 'La contraseña debe tener al menos 8 caracteres';
    }
    
    if (!confirmPassword) {
      passwordErrors.confirmPassword = 'Confirma la nueva contraseña';
    } else if (newPassword !== confirmPassword) {
      passwordErrors.confirmPassword = 'Las contraseñas no coinciden';
    }
    
    return Object.keys(passwordErrors).length === 0;
  }
  
  async function handleProfileUpdate() {
    if (!validateProfileForm()) return;
    
    isUpdatingProfile = true;
    
    try {
      const response = await fetch('/api/v1/auth/profile', {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${$auth.token}`
        },
        body: JSON.stringify({
          first_name: firstName.trim(),
          last_name: lastName.trim()
        })
      });
      
      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.detail || 'Error al actualizar perfil');
      }
      
      const updatedUser = await response.json();
      auth.updateUser(updatedUser);
      toast.success('Perfil actualizado exitosamente');
    } catch (error: any) {
      toast.error(error.message || 'Error al actualizar perfil');
    } finally {
      isUpdatingProfile = false;
    }
  }
  
  async function handlePasswordChange() {
    if (!validatePasswordForm()) return;
    
    isChangingPassword = true;
    
    try {
      const response = await fetch('/api/v1/auth/change-password', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${$auth.token}`
        },
        body: JSON.stringify({
          current_password: currentPassword,
          new_password: newPassword
        })
      });
      
      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.detail || 'Error al cambiar contraseña');
      }
      
      // Clear form
      currentPassword = '';
      newPassword = '';
      confirmPassword = '';
      
      toast.success('Contraseña cambiada exitosamente');
    } catch (error: any) {
      toast.error(error.message || 'Error al cambiar contraseña');
    } finally {
      isChangingPassword = false;
    }
  }
</script>

<svelte:head>
  <title>Mi Perfil - ServiceManager</title>
</svelte:head>

<div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
  <!-- Header -->
  <div class="mb-8">
    <h1 class="text-3xl font-bold text-gray-900">Mi Perfil</h1>
    <p class="text-gray-600 mt-2">
      Gestiona tu información personal y configuración de seguridad
    </p>
  </div>
  
  <div class="space-y-8">
    <!-- Profile Information -->
    <div class="card">
      <div class="card-header">
        <h2 class="text-xl font-semibold text-gray-900">Información Personal</h2>
        <p class="text-gray-600 mt-1">Actualiza tu información básica</p>
      </div>
      
      <div class="card-content">
        <form on:submit|preventDefault={handleProfileUpdate} class="space-y-6">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label for="first-name" class="form-label">
                Nombre <span class="text-red-500">*</span>
              </label>
              <input
                id="first-name"
                type="text"
                class="form-input {profileErrors.firstName ? 'border-red-300' : ''}"
                bind:value={firstName}
                disabled={isUpdatingProfile}
              />
              {#if profileErrors.firstName}
                <p class="form-error">{profileErrors.firstName}</p>
              {/if}
            </div>
            
            <div>
              <label for="last-name" class="form-label">
                Apellido <span class="text-red-500">*</span>
              </label>
              <input
                id="last-name"
                type="text"
                class="form-input {profileErrors.lastName ? 'border-red-300' : ''}"
                bind:value={lastName}
                disabled={isUpdatingProfile}
              />
              {#if profileErrors.lastName}
                <p class="form-error">{profileErrors.lastName}</p>
              {/if}
            </div>
          </div>
          
          <div>
            <label for="email" class="form-label">Correo Electrónico</label>
            <input
              id="email"
              type="email"
              class="form-input bg-gray-50"
              value={$auth.user?.email || ''}
              disabled
            />
            <p class="text-xs text-gray-500 mt-1">
              El correo electrónico no se puede cambiar. Contacta con soporte si necesitas actualizarlo.
            </p>
          </div>
          
          <div class="flex justify-end">
            <button
              type="submit"
              class="btn-primary px-6 py-2"
              disabled={isUpdatingProfile}
            >
              {#if isUpdatingProfile}
                <div class="flex items-center space-x-2">
                  <div class="spinner w-4 h-4"></div>
                  <span>Guardando...</span>
                </div>
              {:else}
                Guardar Cambios
              {/if}
            </button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- Account Security -->
    <div class="card">
      <div class="card-header">
        <h2 class="text-xl font-semibold text-gray-900">Seguridad de la Cuenta</h2>
        <p class="text-gray-600 mt-1">Gestiona tu contraseña y configuración de seguridad</p>
      </div>
      
      <div class="card-content space-y-6">
        <!-- Two-Factor Authentication Status -->
        <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
          <div>
            <h3 class="font-medium text-gray-900">Autenticación de dos factores (2FA)</h3>
            <p class="text-sm text-gray-600">
              {$auth.user?.is_two_factor_enabled 
                ? 'La autenticación de dos factores está habilitada' 
                : 'Mejora la seguridad habilitando 2FA'}
            </p>
          </div>
          <div>
            {#if $auth.user?.is_two_factor_enabled}
              <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800">
                <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                </svg>
                Habilitado
              </span>
            {:else}
              <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-red-100 text-red-800">
                <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
                Deshabilitado
              </span>
            {/if}
          </div>
        </div>
        
        <!-- Change Password Form -->
        <form on:submit|preventDefault={handlePasswordChange} class="space-y-6">
          <h3 class="text-lg font-medium text-gray-900">Cambiar Contraseña</h3>
          
          <div>
            <label for="current-password" class="form-label">
              Contraseña Actual <span class="text-red-500">*</span>
            </label>
            <input
              id="current-password"
              type="password"
              class="form-input {passwordErrors.currentPassword ? 'border-red-300' : ''}"
              bind:value={currentPassword}
              disabled={isChangingPassword}
            />
            {#if passwordErrors.currentPassword}
              <p class="form-error">{passwordErrors.currentPassword}</p>
            {/if}
          </div>
          
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label for="new-password" class="form-label">
                Nueva Contraseña <span class="text-red-500">*</span>
              </label>
              <input
                id="new-password"
                type="password"
                class="form-input {passwordErrors.newPassword ? 'border-red-300' : ''}"
                bind:value={newPassword}
                disabled={isChangingPassword}
              />
              {#if passwordErrors.newPassword}
                <p class="form-error">{passwordErrors.newPassword}</p>
              {/if}
              <p class="text-xs text-gray-500 mt-1">
                Mínimo 8 caracteres
              </p>
            </div>
            
            <div>
              <label for="confirm-password" class="form-label">
                Confirmar Nueva Contraseña <span class="text-red-500">*</span>
              </label>
              <input
                id="confirm-password"
                type="password"
                class="form-input {passwordErrors.confirmPassword ? 'border-red-300' : ''}"
                bind:value={confirmPassword}
                disabled={isChangingPassword}
              />
              {#if passwordErrors.confirmPassword}
                <p class="form-error">{passwordErrors.confirmPassword}</p>
              {/if}
            </div>
          </div>
          
          <div class="flex justify-end">
            <button
              type="submit"
              class="btn-primary px-6 py-2"
              disabled={isChangingPassword}
            >
              {#if isChangingPassword}
                <div class="flex items-center space-x-2">
                  <div class="spinner w-4 h-4"></div>
                  <span>Cambiando...</span>
                </div>
              {:else}
                Cambiar Contraseña
              {/if}
            </button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- Account Information -->
    <div class="card">
      <div class="card-header">
        <h2 class="text-xl font-semibold text-gray-900">Información de la Cuenta</h2>
        <p class="text-gray-600 mt-1">Detalles sobre tu cuenta y organización</p>
      </div>
      
      <div class="card-content">
        <dl class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <dt class="text-sm font-medium text-gray-500">ID de Usuario</dt>
            <dd class="text-sm text-gray-900 font-mono mt-1">#{$auth.user?.id.substring(0, 8)}</dd>
          </div>
          
          <div>
            <dt class="text-sm font-medium text-gray-500">Rol</dt>
            <dd class="text-sm text-gray-900 mt-1">
              {$auth.user?.role === 'CLIENT_ADMIN' ? 'Administrador de Cliente' : 'Usuario de Cliente'}
            </dd>
          </div>
          
          <div>
            <dt class="text-sm font-medium text-gray-500">Estado de la Cuenta</dt>
            <dd class="text-sm mt-1">
              {#if $auth.user?.is_active}
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                  Activa
                </span>
              {:else}
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                  Inactiva
                </span>
              {/if}
            </dd>
          </div>
          
          <div>
            <dt class="text-sm font-medium text-gray-500">Miembro desde</dt>
            <dd class="text-sm text-gray-900 mt-1">
              {$auth.user?.created_at ? new Date($auth.user.created_at).toLocaleDateString('es-ES', {
                day: '2-digit',
                month: 'long',
                year: 'numeric'
              }) : 'N/A'}
            </dd>
          </div>
        </dl>
      </div>
    </div>
  </div>
</div>