import React, { useState, useEffect, useRef } from 'react';
import { Button, Input, Card, Select, Avatar, Modal } from '../../ui';
import { useAuthUser } from '../../../stores/auth.store';
import { showToast } from '../../../utils/toast';
import { useUpdateProfile, useChangePassword, useAuthProfile } from '../../../api/hooks/auth';

interface ProfileSettingsProps {
  onSuccess?: () => void;
  className?: string;
  initialTab?: 'profile' | 'security' | 'preferences' | 'notifications';
}

interface ProfileFormData {
  first_name: string;
  last_name: string;
  email: string;
  phone: string;
  language: string;
  timezone: string;
  avatar?: string;
}


interface NotificationSettings {
  email_notifications: boolean;
  order_notifications: boolean;
  marketing_notifications: boolean;
  security_notifications: boolean;
  low_stock_alerts: boolean;
  production_reminders: boolean;
}

interface PasswordChangeData {
  currentPassword: string;
  newPassword: string;
  confirmNewPassword: string;
}

export const ProfileSettings: React.FC<ProfileSettingsProps> = ({
  onSuccess,
  className,
  initialTab = 'profile'
}) => {
  const user = useAuthUser();
  
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  
  const [activeTab, setActiveTab] = useState<'profile' | 'security' | 'preferences' | 'notifications'>(initialTab);
  
  const updateProfileMutation = useUpdateProfile();
  const changePasswordMutation = useChangePassword();
  const { data: userProfile, isLoading: profileLoading } = useAuthProfile();
  
  const [profileData, setProfileData] = useState<ProfileFormData>({
    first_name: '',
    last_name: '',
    email: '',
    phone: '',
    language: 'es',
    timezone: 'Europe/Madrid',
    avatar: '' // Using empty string to allow Avatar to show default bakery-themed icon
  });
  
  const originalProfileDataRef = useRef<ProfileFormData | null>(null);
  
  // Load profile data from API when available
  useEffect(() => {
    if (userProfile) {
      const profileFormData: ProfileFormData = {
        first_name: userProfile.full_name?.split(' ')[0] || '',
        last_name: userProfile.full_name?.split(' ').slice(1).join(' ') || '',
        email: userProfile.email || '',
        phone: userProfile.phone || '',
        language: userProfile.language || 'es',
        timezone: userProfile.timezone || 'Europe/Madrid',
        avatar: userProfile.avatar || ''
      };
      
      setProfileData(profileFormData);
      originalProfileDataRef.current = profileFormData; // Store original data for reset
    }
  }, [userProfile]);

  const [notificationSettings, setNotificationSettings] = useState<NotificationSettings>({
    email_notifications: true,
    order_notifications: true,
    marketing_notifications: false,
    security_notifications: true,
    low_stock_alerts: true,
    production_reminders: true
  });
  
  const [passwordData, setPasswordData] = useState<PasswordChangeData>({
    currentPassword: '',
    newPassword: '',
    confirmNewPassword: ''
  });
  
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [showPasswords, setShowPasswords] = useState({
    current: false,
    new: false,
    confirm: false
  });
  const [hasChanges, setHasChanges] = useState({
    profile: false,
    bakery: false,
    notifications: false
  });
  const [uploadingImage, setUploadingImage] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [previewImage, setPreviewImage] = useState<string | null>(null);


  const languageOptions = [
    { value: 'es', label: 'Español' },
    { value: 'ca', label: 'Català' },
    { value: 'eu', label: 'Euskera' },
    { value: 'gl', label: 'Galego' },
    { value: 'en', label: 'English' }
  ];

  const timezoneOptions = [
    { value: 'Europe/Madrid', label: 'Madrid (CET/CEST)' },
    { value: 'Atlantic/Canary', label: 'Canarias (WET/WEST)' },
    { value: 'Europe/London', label: 'Londres (GMT/BST)' },
    { value: 'Europe/Paris', label: 'París (CET/CEST)' },
    { value: 'Europe/Rome', label: 'Roma (CET/CEST)' }
  ];

  

  // Profile picture upload handler
  const handleImageUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    // Validate file type
    if (!file.type.startsWith('image/')) {
      showToast.error('Solo se permiten archivos de imagen (JPEG, PNG, GIF, WEBP)', {
        title: 'Error'
      });
      return;
    }

    // Validate file size (max 5MB)
    if (file.size > 5 * 1024 * 1024) {
      showToast.error('El archivo es demasiado grande. Máximo 5MB permitido', {
        title: 'Error'
      });
      return;
    }

    setUploadingImage(true);
    try {
      // Create preview
      const reader = new FileReader();
      reader.onload = (e) => {
        setPreviewImage(e.target?.result as string);
      };
      reader.readAsDataURL(file);

      // Here you would upload to your image service
      // For now, we'll simulate the upload
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      const newImageUrl = URL.createObjectURL(file); // Temporary URL
      setProfileData(prev => ({ ...prev, avatar: newImageUrl }));
      setHasChanges(prev => ({ ...prev, profile: true }));
      
      showToast.success('¡Éxito!', {
        title: 'Foto de perfil actualizada correctamente'
      });
    } catch (error) {
      showToast.error('No se pudo actualizar la foto de perfil', {
        title: 'Error'
      });
    } finally {
      setUploadingImage(false);
      setPreviewImage(null);
    }
  };

  const handleRemoveImage = () => {
    setProfileData(prev => ({ ...prev, avatar: '' }));
    setHasChanges(prev => ({ ...prev, profile: true }));
    setShowDeleteConfirm(false);
  };

  const validateProfileForm = (): boolean => {
    const newErrors: Record<string, string> = {};
    
    if (!profileData.first_name.trim()) {
      newErrors.first_name = 'El nombre es requerido';
    } else if (profileData.first_name.trim().length < 2) {
      newErrors.first_name = 'El nombre debe tener al menos 2 caracteres';
    }

    if (!profileData.last_name.trim()) {
      newErrors.last_name = 'Los apellidos son requeridos';
    } else if (profileData.last_name.trim().length < 2) {
      newErrors.last_name = 'Los apellidos deben tener al menos 2 caracteres';
    }
    
    if (!profileData.email.trim()) {
      newErrors.email = 'El email es requerido';
    } else if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(profileData.email)) {
      newErrors.email = 'Por favor, ingrese un email válido';
    }
    
    if (profileData.phone && !/^(\+34|0034|34)?[6-9][0-9]{8}$/.test(profileData.phone.replace(/\s/g, ''))) {
      newErrors.phone = 'Por favor, ingrese un teléfono español válido (ej: +34 600 000 000)';
    }

    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };


  const validatePasswordForm = (): boolean => {
    const newErrors: Record<string, string> = {};
    
    if (!passwordData.currentPassword) {
      newErrors.currentPassword = 'La contraseña actual es requerida';
    }
    
    if (!passwordData.newPassword) {
      newErrors.newPassword = 'La nueva contraseña es requerida';
    } else {
      // Use simpler validation for now to match backend exactly
      if (passwordData.newPassword.length < 8) {
        newErrors.newPassword = 'La contraseña debe tener al menos 8 caracteres';
      } else if (passwordData.newPassword.length > 128) {
        newErrors.newPassword = 'La contraseña no puede exceder 128 caracteres';
      } else if (!/[A-Z]/.test(passwordData.newPassword)) {
        newErrors.newPassword = 'La contraseña debe contener al menos una letra mayúscula';
      } else if (!/[a-z]/.test(passwordData.newPassword)) {
        newErrors.newPassword = 'La contraseña debe contener al menos una letra minúscula';
      } else if (!/\d/.test(passwordData.newPassword)) {
        newErrors.newPassword = 'La contraseña debe contener al menos un número';
      }
    }
    
    if (!passwordData.confirmNewPassword) {
      newErrors.confirmNewPassword = 'Confirma tu nueva contraseña';
    } else if (passwordData.newPassword !== passwordData.confirmNewPassword) {
      newErrors.confirmNewPassword = 'Las contraseñas no coinciden';
    }
    
    if (passwordData.currentPassword === passwordData.newPassword) {
      newErrors.newPassword = 'La nueva contraseña debe ser diferente a la actual';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleProfileSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateProfileForm()) {
      return;
    }

    try {
      await updateProfileMutation.mutateAsync({
        full_name: `${profileData.first_name} ${profileData.last_name}`.trim() || profileData.first_name,
        email: profileData.email,
        phone: profileData.phone,
        language: profileData.language,
        timezone: profileData.timezone,
      });
      
      setHasChanges(false);
      showToast.success('¡Éxito!', {
        title: 'Perfil actualizado correctamente'
      });
      onSuccess?.();
    } catch (err) {
      showToast.error('No se pudo actualizar el perfil', {
        title: 'Error'
      });
    }
  };

  const handlePasswordSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validatePasswordForm()) {
      return;
    }

    try {
      await changePasswordMutation.mutateAsync({
        current_password: passwordData.currentPassword,
        new_password: passwordData.newPassword,
      });
      
      showToast.success('¡Éxito!', {
        title: 'Contraseña cambiada correctamente'
      });
      
      setPasswordData({
        currentPassword: '',
        newPassword: '',
        confirmNewPassword: ''
      });
    } catch (error) {
      showToast.error('No se pudo cambiar la contraseña', {
        title: 'Error'
      });
    }
  };

  const handleProfileInputChange = (field: keyof ProfileFormData) => (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setProfileData(prev => ({ ...prev, [field]: value }));
    setHasChanges(prev => ({ ...prev, profile: true }));
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: undefined }));
    }
  };

  const handleSelectChange = (field: keyof ProfileFormData) => (value: string) => {
    setProfileData(prev => ({ ...prev, [field]: value }));
    setHasChanges(prev => ({ ...prev, profile: true }));
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: undefined }));
    }
  };

  const handlePasswordInputChange = (field: keyof PasswordChangeData) => (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setPasswordData(prev => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: undefined }));
    }
  };

  const togglePasswordVisibility = (field: 'current' | 'new' | 'confirm') => {
    setShowPasswords(prev => ({
      ...prev,
      [field]: !prev[field]
    }));
  };

  const tabs = [
    { id: 'profile' as const, label: 'Perfil', icon: 'M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z' },
    { id: 'security' as const, label: 'Seguridad', icon: 'M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z' },
    { id: 'preferences' as const, label: 'Preferencias', icon: 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z' }
  ];

  // User data for display - based on actual profile data
  const displayUser = {
    first_name: profileData.first_name || '',
    last_name: profileData.last_name || '',
    email: profileData.email || '',
    bakery_name: user?.tenant_id ? 'Current Bakery' : 'No Bakery Assigned',
    avatar: profileData.avatar || ''
  };

  return (
    <div className={`space-y-6 ${className || ''}`}>
      {/* Header */}
      <Card className="p-8">
        <div className="flex items-center space-x-6">
          <div className="relative">
            <Avatar
              src={displayUser.avatar || undefined}
              alt={`${displayUser.first_name} ${displayUser.last_name}` || 'Usuario'}
              name={displayUser.avatar ? `${displayUser.first_name} ${displayUser.last_name}` : undefined}
              size="xl"
              className="w-20 h-20 border-4 border-background-primary shadow-lg"
            />
            <div className="absolute -bottom-1 -right-1 w-6 h-6 bg-color-success rounded-full border-2 border-background-primary"></div>
          </div>
          <div className="flex-1">
            <h1 className="text-3xl font-bold text-text-primary mb-2">
              {displayUser.first_name} {displayUser.last_name}
            </h1>
            <p className="text-text-secondary text-lg mb-1">{displayUser.email}</p>
            <p className="text-sm text-text-tertiary flex items-center">
              <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
              </svg>
              Trabajando en {displayUser.bakery_name}
            </p>
          </div>
          <div className="text-right">
            <div className="inline-flex items-center px-3 py-1 rounded-full text-sm bg-color-success/10 text-color-success mb-2">
              <div className="w-2 h-2 bg-color-success rounded-full mr-2"></div>
              En línea
            </div>
            <p className="text-xs text-text-tertiary">Última vez activo: ahora</p>
          </div>
        </div>
      </Card>

      {/* Tabs */}
      <Card className="overflow-hidden">
        <div className="border-b border-border-primary">
          <nav className="flex">
            {tabs.map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`flex items-center space-x-2 px-6 py-4 text-sm font-medium transition-colors ${
                  activeTab === tab.id
                    ? 'text-color-primary border-b-2 border-color-primary'
                    : 'text-text-secondary hover:text-text-primary'
                }`}
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d={tab.icon} />
                </svg>
                <span>{tab.label}</span>
              </button>
            ))}
          </nav>
        </div>

        <div className="p-8">
          {activeTab === 'profile' && (
            <div className="max-w-4xl mx-auto">
              {/* Profile Photo Section */}
              <div className="flex items-center space-x-8 mb-8 p-6 bg-background-secondary rounded-lg">
                <div className="relative">
                  <Avatar
                    src={profileData.avatar || undefined}
                    alt={`${profileData.first_name} ${profileData.last_name}` || 'Usuario'}
                    name={profileData.avatar ? `${profileData.first_name} ${profileData.last_name}` : undefined}
                    size="xl"
                    className="w-24 h-24"
                  />
                  <button
                    type="button"
                    onClick={() => fileInputRef.current?.click()}
                    className="absolute -bottom-2 -right-2 bg-color-primary text-white rounded-full p-2 shadow-lg hover:bg-color-primary-dark transition-colors"
                    disabled={isLoading}
                  >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" />
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
                    </svg>
                  </button>
                  <input
                    ref={fileInputRef}
                    type="file"
                    accept="image/*"
                    onChange={handleImageUpload}
                    className="hidden"
                  />
                </div>
                <div className="flex-1">
                  <h2 className="text-2xl font-bold text-text-primary mb-2">
                    {profileData.first_name} {profileData.last_name}
                  </h2>
                  <p className="text-text-secondary text-lg mb-2">{profileData.email}</p>
                  <p className="text-text-tertiary text-sm">Última actualización: Hace 2 días</p>
                </div>
                {uploadingImage && (
                  <div className="text-color-primary">
                    <svg className="animate-spin h-6 w-6" fill="none" viewBox="0 0 24 24">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                  </div>
                )}
              </div>

              <form onSubmit={handleProfileSubmit} className="space-y-8">
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
                  {/* Personal Information */}
                  <div className="space-y-6">
                    <h3 className="text-xl font-semibold text-text-primary border-b border-border-primary pb-3">
                      Información Personal
                    </h3>
                    
                    <div className="space-y-4">
                      <Input
                        label="Nombre"
                        value={profileData.first_name}
                        onChange={handleProfileInputChange('first_name')}
                        error={errors.first_name}
                        disabled={isLoading}
                        required
                        size="lg"
                      />
                      
                      <Input
                        label="Apellidos"
                        value={profileData.last_name}
                        onChange={handleProfileInputChange('last_name')}
                        error={errors.last_name}
                        disabled={isLoading}
                        required
                        size="lg"
                      />
                      
                      <Input
                        type="email"
                        label="Correo Electrónico"
                        value={profileData.email}
                        onChange={handleProfileInputChange('email')}
                        error={errors.email}
                        disabled={isLoading}
                        required
                        size="lg"
                      />
                      
                      <Input
                        type="tel"
                        label="Teléfono"
                        value={profileData.phone}
                        onChange={handleProfileInputChange('phone')}
                        error={errors.phone}
                        disabled={isLoading}
                        placeholder="+34 600 000 000"
                        size="lg"
                      />
                    </div>
                  </div>

                  {/* Preferences */}
                  <div className="space-y-6">
                    <h3 className="text-xl font-semibold text-text-primary border-b border-border-primary pb-3">
                      Preferencias
                    </h3>
                    
                    <div className="space-y-4">
                      <Select
                        label="Idioma"
                        options={languageOptions}
                        value={profileData.language}
                        onChange={handleSelectChange('language')}
                        disabled={isLoading}
                        size="lg"
                      />
                      
                      <Select
                        label="Zona Horaria"
                        options={timezoneOptions}
                        value={profileData.timezone}
                        onChange={handleSelectChange('timezone')}
                        disabled={isLoading}
                        size="lg"
                      />
                    </div>
                  </div>
                </div>
                
                <div className="flex justify-end space-x-4 pt-8 border-t border-border-primary">
                  <Button
                    type="button"
                    variant="outline"
                    size="lg"
                    onClick={() => {
                      // Reset to original profile data
                      if (originalProfileDataRef.current) {
                        setProfileData(originalProfileDataRef.current);
                      }
                      setHasChanges(prev => ({ ...prev, profile: false }));
                      setErrors({});
                    }}
                    disabled={!hasChanges.profile || isLoading}
                  >
                    Cancelar
                  </Button>
                  <Button
                    type="submit"
                    variant="primary"
                    size="lg"
                    isLoading={isLoading}
                    loadingText="Guardando..."
                    disabled={!hasChanges.profile}
                  >
                    Guardar Cambios
                  </Button>
                </div>
              </form>
            </div>
          )}

          {activeTab === 'security' && (
            <form onSubmit={handlePasswordSubmit} className="space-y-6 max-w-md">
              <h3 className="text-lg font-semibold text-text-primary border-b border-border-primary pb-2">
                Cambiar Contraseña
              </h3>
              
              <Input
                type={showPasswords.current ? 'text' : 'password'}
                label="Contraseña Actual"
                value={passwordData.currentPassword}
                onChange={handlePasswordInputChange('currentPassword')}
                error={errors.currentPassword}
                disabled={isLoading}
                required
                rightIcon={
                  <button
                    type="button"
                    onClick={() => togglePasswordVisibility('current')}
                    className="text-text-secondary hover:text-text-primary"
                  >
                    {showPasswords.current ? (
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
                      </svg>
                    ) : (
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                      </svg>
                    )}
                  </button>
                }
              />
              
              <Input
                type={showPasswords.new ? 'text' : 'password'}
                label="Nueva Contraseña"
                value={passwordData.newPassword}
                onChange={handlePasswordInputChange('newPassword')}
                error={errors.newPassword}
                disabled={isLoading}
                required
                rightIcon={
                  <button
                    type="button"
                    onClick={() => togglePasswordVisibility('new')}
                    className="text-text-secondary hover:text-text-primary"
                  >
                    {showPasswords.new ? (
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
                      </svg>
                    ) : (
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                      </svg>
                    )}
                  </button>
                }
              />
              
              <Input
                type={showPasswords.confirm ? 'text' : 'password'}
                label="Confirmar Nueva Contraseña"
                value={passwordData.confirmNewPassword}
                onChange={handlePasswordInputChange('confirmNewPassword')}
                error={errors.confirmNewPassword}
                disabled={isLoading}
                required
                rightIcon={
                  <button
                    type="button"
                    onClick={() => togglePasswordVisibility('confirm')}
                    className="text-text-secondary hover:text-text-primary"
                  >
                    {showPasswords.confirm ? (
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
                      </svg>
                    ) : (
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                      </svg>
                    )}
                  </button>
                }
              />
              
              <Button
                type="submit"
                variant="primary"
                isLoading={isLoading}
                loadingText="Actualizando..."
              >
                Cambiar Contraseña
              </Button>
            </form>
          )}

          {activeTab === 'preferences' && (
            <div className="space-y-6">
              <h3 className="text-lg font-semibold text-text-primary border-b border-border-primary pb-2">
                Preferencias
              </h3>
              
              <div className="text-text-secondary">
                <p>Configuraciones de preferencias estarán disponibles próximamente.</p>
                <div className="mt-4 space-y-2 text-sm">
                  <p>• Configuración de idioma</p>
                  <p>• Zona horaria</p>
                  <p>• Formato de fecha y hora</p>
                  <p>• Notificaciones</p>
                  <p>• Tema de la aplicación</p>
                </div>
              </div>
            </div>
          )}
        </div>
      </Card>
    </div>
  );
};

export default ProfileSettings;
