import { Component, inject, OnInit, TemplateRef, ViewChild, ChangeDetectorRef, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { NgIcon } from '@ng-icons/core';
import { NgbNavModule, NgbModal, NgbModalModule } from '@ng-bootstrap/ng-bootstrap';
import { catchError, map, of, Subject, takeUntil } from 'rxjs';

import { MerchantUsersService } from './merchant-users.service';
import { RoleManagementService } from '@core/services/hub-users-roles-management.service';
import { AuthService } from '@core/services/auth.service';
import { PageTitle } from '@app/components/page-title/page-title';
import { MerchantUsersList } from './merchant-users-list/merchant-users-list';
import { MerchantUserProfile } from './merchant-users-profile/merchant-users-profile';

import { 
  PaginatedUserResponse,
  ResetPasswordDto,
  User,
  UserRole,
  UserType
} from '@core/models/dcb-bo-hub-user.model';
import { HubUsersService } from './hub-users.service';

@Component({
  selector: 'app-merchant-users',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    NgIcon,
    NgbNavModule,
    NgbModalModule,
    PageTitle,
    MerchantUsersList,
    MerchantUserProfile
  ],
  templateUrl: './merchant-users.html',
})
export class MerchantUsersManagement implements OnInit, OnDestroy {
  private modalService = inject(NgbModal);
  private authService = inject(AuthService);
  private merchantUsersService = inject(MerchantUsersService);
  private hubUsersService = inject(HubUsersService);
  protected roleService = inject(RoleManagementService);
  private cdRef = inject(ChangeDetectorRef);
  private destroy$ = new Subject<void>();

  // Configuration
  readonly UserRole = UserRole;
  
  // Propriétés de configuration
  pageTitle: string = 'Gestion des Utilisateurs Marchands';
  pageSubtitle: string = 'Administrez les utilisateurs de votre équipe marchande';
  badge: any = { icon: 'lucideBuilding', text: 'Merchant Users' };

  // État de l'interface
  activeTab: 'list' | 'profile' = 'list';
  selectedUserId: string | null = null;

  // Gestion des permissions
  currentUserRole: UserRole | null = null;
  currentUserType: UserType | null = null;
  currentMerchantPartnerId: string = '';
  userPermissions: any = null;
  canCreateUsers = false;
  canDeleteUsers = false;
  canManageRoles = false;

  // Formulaire de création
  newUser: {
    username: string;
    email: string;
    firstName: string;
    lastName: string;
    password: string;
    role: UserRole;
    enabled: boolean;
    emailVerified: boolean;
    merchantPartnerId: string;
    userType: UserType;
  } = this.getDefaultUserForm();

  // États des opérations
  creatingUser = false;
  createUserError = '';
  resettingPassword = false;
  resetPasswordError = '';
  resetPasswordSuccess = '';

  newPassword = '';
  temporaryPassword = false;

  deletingUser = false;
  deleteUserError = '';

  selectedUserForReset: any = null;
  selectedUserForDelete: any = null;

  // UX améliorations
  showPassword = false;
  showNewPassword = false;

  // Références aux templates de modals
  @ViewChild('createUserModal') createUserModal!: TemplateRef<any>;
  @ViewChild('resetPasswordModal') resetPasswordModal!: TemplateRef<any>;
  @ViewChild('deleteUserModal') deleteUserModal!: TemplateRef<any>;

  // Références aux composants enfants
  @ViewChild(MerchantUsersList) merchantUsersList!: MerchantUsersList;

  // Rôles disponibles
  availableRoles: { value: UserRole; label: string; description: string }[] = [];
  assignableRoles: UserRole[] = [];

  merchantPartners: User[] = [];
  loadingMerchantPartners = false;
  merchantPartnersError = '';
  selectedMerchantPartnerId: string = '';
  
  ngOnInit() {
    this.activeTab = 'list';
    this.loadCurrentUserPermissions();
    this.loadAvailableRoles();
    this.newUser.role = UserRole.DCB_PARTNER_SUPPORT;

    // Charger la liste des partenaires marchands (pour les admins Hub)
    if (this.currentUserRole === UserRole.DCB_ADMIN || 
        this.currentUserRole === UserRole.DCB_SUPPORT) {

          this.loadMerchantPartners();
    }

    // Initialiser le formulaire selon le contexte
    this.initializeMerchantPartner();
  }

  // Initialiser le merchant partner selon le contexte
  initializeMerchantPartner() {
    if (this.currentUserRole === UserRole.DCB_PARTNER && this.currentMerchantPartnerId) {
      // Auto-sélection pour DCB_PARTNER
      this.selectedMerchantPartnerId = this.currentMerchantPartnerId;
    }else if (this.currentUserRole === UserRole.DCB_PARTNER_ADMIN && this.currentMerchantPartnerId) {
      // Auto-sélection pour DCB_PARTNER_ADMIN
      this.selectedMerchantPartnerId = this.currentMerchantPartnerId;
    } else if ((this.currentUserRole === UserRole.DCB_ADMIN || 
                this.currentUserRole === UserRole.DCB_SUPPORT) && 
               this.isMerchantRole(this.newUser.role)) {
      // Forcer la sélection pour les admins Hub créant des users marchands
      this.selectedMerchantPartnerId = '';
    }
  }

  onRoleSelectionChange(selectedRole: UserRole) {
    this.newUser.role = selectedRole;
  }

  onPartnerSelectionChange(selectedPartner: User) {
    this.newUser.merchantPartnerId = this.selectedMerchantPartnerId || '';

    this.currentMerchantPartnerId = this.selectedMerchantPartnerId || ''
  }

  /**
   * Recharge les partenaires marchands (pour retry)
   */
  reloadMerchantPartners(): void {
    console.log('🔄 Rechargement des partenaires marchands...');
    this.loadMerchantPartners();
  }


  /**
   * Charge la liste des partenaires marchands
   */
  loadMerchantPartners(): void {
    this.loadingMerchantPartners = true;
    this.merchantPartnersError = '';

    console.log('🔄 Chargement des partenaires marchands...');

    this.hubUsersService.getAllDcbPartners()
      .pipe(
        map((response: PaginatedUserResponse) => response.users),
        takeUntil(this.destroy$),
        catchError(error => {
          console.error('Error loading hub users:', error);
          this.loadingMerchantPartners = false;
          this.merchantPartnersError = 'Impossible de charger la liste des partenaires marchands';
          return of([] as User[]);
        })
      )
      .subscribe(
        {next: (partners) => {
          this.merchantPartners = partners;
          this.loadingMerchantPartners = false;
          
          console.log(`✅ ${partners.length} partenaires marchands chargés`, partners);
        
        },
        error: (error) => {
          console.error('❌ Erreur lors du chargement des partenaires marchands:', error);
          this.loadingMerchantPartners = false;
          this.merchantPartnersError = 'Impossible de charger la liste des partenaires marchands';
        }
    });
  }

  /**
   * Vérifie si l'utilisateur connecté est un DCB_PARTNER ou DCB_PARTNER_ADMIN
   */
  get isPartnerUser(): boolean {
    return this.currentUserRole === UserRole.DCB_PARTNER || 
           this.currentUserRole === UserRole.DCB_PARTNER_ADMIN;
  }

  /**
   * Vérifie si on doit afficher le champ Merchant Partner ID
   */
  get showMerchantPartnerIdField(): boolean {
    return this.isPartnerUser && this.isMerchantRole(this.newUser.role);
  }

  get showMerchantPartnerField(): boolean {
    if (this.isMerchantRole(this.newUser.role)) {
      return true;
    }
    return false;
  }

  get requireMerchantPartnerSelection(): boolean {
    // Si l'utilisateur connecté est un admin/support Hub ET qu'il crée un utilisateur marchand
    const isHubAdminCreatingMerchant = 
      (this.currentUserRole === UserRole.DCB_ADMIN || 
       this.currentUserRole === UserRole.DCB_SUPPORT) &&
      this.isMerchantRole(this.newUser.role);
    return isHubAdminCreatingMerchant;
  }

  get merchantSelectionHelpText(): string {
    if (this.currentUserRole === UserRole.DCB_ADMIN || 
        this.currentUserRole === UserRole.DCB_SUPPORT) {
      return 'En tant qu\'administrateur Hub, vous devez sélectionner un partenaire marchand pour cet utilisateur';
    }

    return 'Sélectionnez le partenaire marchand auquel cet utilisateur sera associé';
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }

  /**
   * Initialise les permissions de l'utilisateur courant
   */
  private loadCurrentUserPermissions(): void {
    this.authService.getUserProfile()
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (user) => {
          this.currentUserRole = this.extractUserRole(user);
          this.currentMerchantPartnerId = this.extractMerchantPartnerId(user);
          this.currentUserType = this.extractUserType(user);

          console.log(`MERCHANT User ROLE: ${this.currentUserRole}`);
          console.log(`Merchant Partner ID: ${this.currentMerchantPartnerId}`);

          if (this.currentUserRole) {
            this.roleService.setCurrentUserRole(this.currentUserRole);
            this.userPermissions = this.roleService.getPermissionsForRole(this.currentUserRole);
            this.canCreateUsers = this.roleService.canCreateUsers(this.currentUserRole);
            this.canDeleteUsers = this.roleService.canDeleteUsers(this.currentUserRole);
            this.canManageRoles = this.roleService.canManageRoles(this.currentUserRole);
            
            this.assignableRoles = this.roleService.getAssignableRoles(this.currentUserRole);
            console.log('Assignable roles:', this.assignableRoles);
          }

          // Initialiser le merchantPartnerId
          this.newUser.merchantPartnerId = this.currentMerchantPartnerId;
        },
        error: (error) => {
          console.error('Error loading user profile:', error);
          this.fallbackPermissions();
        }
      });
  }

  /**
   * Extraire le rôle de l'utilisateur
   */
  private extractUserRole(user: any): UserRole | null {
    const userRoles = this.authService.getCurrentUserRoles();
    if (userRoles && userRoles.length > 0) {
      return userRoles[0];
    }
    return null;
  }

  /**
   * Extraire le type de l'utilisateur
   */
  private extractUserType(user: any): UserType | null {
    const userType = this.authService.getCurrentUserType();
    return userType || null;
  }

  /**
   * Extraire le merchantPartnerId
   */
  private extractMerchantPartnerId(user: any): string {
    if (user?.merchantPartnerId) {
      return user.merchantPartnerId;
    }
    return this.authService.getCurrentMerchantPartnerId() || '';
  }

  /**
   * Fallback en cas d'erreur de chargement du profil
   */
  private fallbackPermissions(): void {
    this.currentUserRole = this.authService.getCurrentUserRole();
    this.currentMerchantPartnerId = this.authService.getCurrentMerchantPartnerId() || '';
    
    if (this.currentUserRole) {
      this.canCreateUsers = this.roleService.canCreateUsers(this.currentUserRole);
      this.canDeleteUsers = this.roleService.canDeleteUsers(this.currentUserRole);
      this.canManageRoles = this.roleService.canManageRoles(this.currentUserRole);
    }
  }

  /**
   * Charge les rôles disponibles
   */
  private loadAvailableRoles(): void {
    this.merchantUsersService.getAvailableMerchantRoles()
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (response) => {
          this.availableRoles = response.roles.map(role => ({
            value: role.value,
            label: role.label,
            description: role.description
          }));
          console.log('Available merchant roles loaded:', this.availableRoles);
        },
        error: (error) => {
          console.error('Error loading available roles:', error);
          this.availableRoles = this.getFallbackRoles();
        }
      });
  }

  /**
   * Rôles par défaut en cas d'erreur
   */
  private getFallbackRoles(): any[] {
    return [
      { value: UserRole.DCB_PARTNER_ADMIN, label: 'Partner Admin', description: 'Administrateur partenaire' },
      { value: UserRole.DCB_PARTNER_MANAGER, label: 'Partner Manager', description: 'Manager partenaire' },
      { value: UserRole.DCB_PARTNER_SUPPORT, label: 'Partner Support', description: 'Support partenaire' }
    ];
  }

  private getDefaultUserForm() {
    return {
      username: '',
      email: '',
      firstName: '',
      lastName: '',
      password: '',
      role: UserRole.DCB_PARTNER_SUPPORT,
      enabled: true,
      emailVerified: false,
      merchantPartnerId: '',
      userType: UserType.MERCHANT_PARTNER
    };
  }

  // ==================== MÉTHODES D'INTERFACE ====================

  userProfiles: { [userId: string]: any } = {}; // Stocker les profils par userId
  users: any[] = []; // Liste des utilisateurs
  loadingProfiles: { [userId: string]: boolean } = {}; // État de chargement par user

  // Méthode pour changer d'onglet
  showTab(tab: 'list' | 'profile', userId?: string) {
    console.log(`Switching to tab: ${tab}`, userId ? `for user ${userId}` : '');
    this.activeTab = tab;
    
    if (userId) {
      this.selectedUserId = userId;
      // Charger le profil si pas déjà chargé
      if (!this.userProfiles[userId]) {
        this.loadUserProfile(userId);
      }
    } else {
      this.selectedUserId = null;
    }
  }

  // Charger un profil spécifique
  loadUserProfile(userId: string) {
    if (this.loadingProfiles[userId]) return; // Éviter les doublons
    
    this.loadingProfiles[userId] = true;
    
    this.merchantUsersService.getMerchantUserById(userId).subscribe({
      next: (profile) => {
        this.userProfiles[userId] = profile;
        this.loadingProfiles[userId] = false;
        console.log(`Profile loaded for user ${userId}:`, profile);
      },
      error: (error) => {
        console.error(`Error loading profile for user ${userId}:`, error);
        this.loadingProfiles[userId] = false;
      }
    });
  }

  // Getter pour le profil actuel
  get currentProfile() {
    return this.selectedUserId ? this.userProfiles[this.selectedUserId] : null;
  }

  // Getter pour l'état de chargement
  get isLoadingProfile() {
    return this.selectedUserId ? this.loadingProfiles[this.selectedUserId] : false;
  }


  backToList() {
    console.log('🔙 Returning to list view');
    this.activeTab = 'list';
    this.selectedUserId = null;
  }

  // Méthodes de gestion des événements du composant enfant
  onUserSelected(userId: string) {
    this.showTab('profile', userId);
  }

  onResetPasswordRequested(event: any) {
    const userId = typeof event === 'string' ? event : event.detail || event;
    this.openResetPasswordModal(userId);
  }

  onDeleteUserRequested(event: any) {
    const userId = typeof event === 'string' ? event : event.detail || event;
    this.openDeleteUserModal(userId);
  }

  // ==================== GESTION DES MODALS ====================

  openModal(content: TemplateRef<any>, size: 'sm' | 'lg' | 'xl' = 'lg') {
    this.modalService.open(content, { 
      size: size,
      centered: true,
      scrollable: true 
    });
  }

  // Méthode pour ouvrir le modal de création d'utilisateur
  openCreateUserModal() {
    if (!this.canCreateUsers) {
      console.warn('User does not have permission to create users');
      return;
    }

    this.resetUserForm();
    this.createUserError = '';
    this.openModal(this.createUserModal);
  }

  private resetUserForm() {
    this.newUser = {
      username: '',
      email: '',
      firstName: '',
      lastName: '',
      password: '',
      role: UserRole.DCB_PARTNER_SUPPORT,
      enabled: true,
      emailVerified: false,
      merchantPartnerId: this.selectedMerchantPartnerId,
      userType: UserType.MERCHANT_PARTNER,
    };
    console.log('🔄 Merchant user form reset');
  }

  // Méthode pour ouvrir le modal de réinitialisation de mot de passe
  openResetPasswordModal(userId: string) {
    this.merchantUsersService.getMerchantUserById(userId)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (user) => {
          this.selectedUserForReset = user;
          this.newPassword = '';
          this.temporaryPassword = false;
          this.resetPasswordError = '';
          this.resetPasswordSuccess = '';
          this.openModal(this.resetPasswordModal);
          console.log('✅ Merchant user loaded for password reset:', user.username);
        },
        error: (error) => {
          console.error('❌ Error loading merchant user for password reset:', error);
          this.resetPasswordError = 'Erreur lors du chargement de l\'utilisateur';
          this.cdRef.detectChanges();
        }
      });
  }

  // Méthode pour ouvrir le modal de suppression
  openDeleteUserModal(userId: string) {
    if (!this.canDeleteUsers) {
      console.warn('User does not have permission to delete users');
      return;
    }

    console.log(`🗑️ Opening delete modal for merchant user: ${userId}`);
    this.merchantUsersService.getMerchantUserById(userId)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (user) => {
          this.selectedUserForDelete = user;
          this.deleteUserError = '';
          this.openModal(this.deleteUserModal);
          console.log('✅ Merchant user loaded for deletion:', user.username);
        },
        error: (error) => {
          console.error('❌ Error loading merchant user for deletion:', error);
          this.deleteUserError = 'Erreur lors du chargement de l\'utilisateur';
          this.cdRef.detectChanges();
        }
      });
  }


  // ==================== OPÉRATIONS CRUD ====================

  createUser() {
    if (!this.canCreateUsers) {
      this.createUserError = 'Vous n\'avez pas la permission de créer des utilisateurs';
      return;
    }

    const validation = this.validateUserForm();
    if (!validation.isValid) {
      this.createUserError = validation.error!;
      console.error('❌ Form validation failed:', validation.error);
      return;
    }

    // Vérifier la permission pour attribuer le rôle sélectionné
    if (!this.canAssignRole(this.newUser.role)) {
      this.createUserError = `Vous n'avez pas la permission d'attribuer le rôle: ${this.getRoleLabel(this.newUser.role)}`;
      return;
    }

    // Validation spécifique au contexte marchand
    if (!this.newUser.merchantPartnerId) {
      this.createUserError = 'Merchant Partner ID est requis pour les utilisateurs marchands';
      return;
    }

    this.creatingUser = true;
    this.createUserError = '';

    console.log('📤 Creating merchant user with data:', this.newUser);

    this.merchantUsersService.createMerchantUser(this.newUser)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (createdUser) => {
          console.log('✅ Merchant user created successfully:', createdUser);
          this.creatingUser = false;
          this.modalService.dismissAll();
          this.refreshUsersList();
          this.cdRef.detectChanges();
        },
        error: (error) => {
          console.error('❌ Error creating merchant user:', error);
          this.creatingUser = false;
          this.createUserError = this.getErrorMessage(error);
          this.cdRef.detectChanges();
        }
      });
  }

  /**
   * Vérifie si un rôle est un rôle marchand
   */
  isMerchantRole(role: UserRole): boolean {
    const merchantRoles = [
      UserRole.DCB_PARTNER_ADMIN,
      UserRole.DCB_PARTNER_MANAGER,
      UserRole.DCB_PARTNER_SUPPORT
    ];

    return merchantRoles.includes(role);
  }

  /**
   * Vérifie si l'utilisateur peut attribuer un rôle spécifique
   */
  canAssignRole(targetRole: UserRole): boolean {
    return this.roleService.canAssignRole(this.currentUserRole, targetRole);
  }

  // Réinitialiser le mot de passe
  confirmResetPassword() {
    if (!this.selectedUserForReset || !this.newPassword || this.newPassword.length < 8) {
      this.resetPasswordError = 'Veuillez saisir un mot de passe valide (au moins 8 caractères).';
      console.error('❌ Password reset validation failed');
      return;
    }

    console.log('🔑 Confirming password reset for merchant user:', this.selectedUserForReset.username);

    this.resettingPassword = true;
    this.resetPasswordError = '';
    this.resetPasswordSuccess = '';

    const resetPasswordDto: ResetPasswordDto = {
      newPassword: this.newPassword,
      temporary: this.temporaryPassword
    };

    this.merchantUsersService.resetMerchantUserPassword(
      this.selectedUserForReset.id, 
      resetPasswordDto
    ).pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (response) => {
          console.log('✅ Merchant user password reset successfully');
          this.resettingPassword = false;
          this.resetPasswordSuccess = 'Mot de passe réinitialisé avec succès !';
          this.cdRef.detectChanges();
          
          // Fermer le modal après 2 secondes
          setTimeout(() => {
            this.modalService.dismissAll();
          }, 2000);
        },
        error: (error) => {
          console.error('❌ Error resetting merchant user password:', error);
          this.resettingPassword = false;
          this.resetPasswordError = this.getResetPasswordErrorMessage(error);
          this.cdRef.detectChanges();
        }
      });
  }

  confirmDeleteUser() {
    if (!this.selectedUserForDelete || !this.canDeleteUsers) {
      console.error('❌ No merchant user selected for deletion or no permission');
      return;
    }

    console.log('🗑️ Confirming merchant user deletion:', this.selectedUserForDelete.username);

    this.deletingUser = true;
    this.deleteUserError = '';

    this.merchantUsersService.deleteMerchantUser(this.selectedUserForDelete.id)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: () => {
          console.log('✅ Merchant user deleted successfully');
          this.deletingUser = false;
          this.modalService.dismissAll();
          this.refreshUsersList();
          this.cdRef.detectChanges();
        },
        error: (error) => {
          console.error('❌ Error deleting merchant user:', error);
          this.deletingUser = false;
          this.deleteUserError = this.getDeleteErrorMessage(error);
          this.cdRef.detectChanges();
        }
      });
  }

  // ==================== MÉTHODES UTILITAIRES ====================

  private refreshUsersList(): void {
    if (this.merchantUsersList && typeof this.merchantUsersList.refreshData === 'function') {
      console.log('🔄 Refreshing merchant users list...');
      this.merchantUsersList.refreshData();
    } else {
      console.warn('❌ MerchantUsersList component not available for refresh');
      this.showTab('list');
    }
  }

  // Méthodes proxy pour le template
  getRoleBadgeClass(role: UserRole): string {
    return this.roleService.getRoleBadgeClass(role);
  }

  getRoleLabel(role: UserRole): string {
    return this.roleService.getRoleLabel(role);
  }

  getRoleIcon(role: UserRole): string {
    return this.roleService.getRoleIcon(role);
  }

  getRoleDescription(role: UserRole): string {
    const roleInfo = this.availableRoles.find(r => r.value === role);
    return roleInfo?.description || 'Description non disponible';
  }

  getUserInitials(user: any): string {
    return (user.firstName?.charAt(0) || '') + (user.lastName?.charAt(0) || '') || 'U';
  }

  // ==================== GESTION DES ERREURS ====================

  private getErrorMessage(error: any): string {
    if (error.error?.message) {
      return error.error.message;
    }
    if (error.status === 400) {
      return 'Données invalides. Vérifiez les champs du formulaire.';
    }
    if (error.status === 409) {
      return 'Un utilisateur avec ce nom d\'utilisateur ou email existe déjà.';
    }
    if (error.status === 403) {
      return 'Vous n\'avez pas les permissions nécessaires pour cette action.';
    }
    return 'Erreur lors de la création de l\'utilisateur. Veuillez réessayer.';
  }

  private getResetPasswordErrorMessage(error: any): string {
    if (error.error?.message) {
      return error.error.message;
    }
    if (error.status === 404) {
      return 'Utilisateur non trouvé.';
    }
    if (error.status === 400) {
      return 'Le mot de passe ne respecte pas les critères de sécurité.';
    }
    if (error.status === 403) {
      return 'Vous n\'avez pas les permissions pour réinitialiser ce mot de passe.';
    }
    return 'Erreur lors de la réinitialisation du mot de passe. Veuillez réessayer.';
  }

  private getDeleteErrorMessage(error: any): string {
    if (error.error?.message) {
      return error.error.message;
    }
    if (error.status === 404) {
      return 'Utilisateur non trouvé.';
    }
    if (error.status === 403) {
      return 'Vous n\'avez pas les permissions pour supprimer cet utilisateur.';
    }
    if (error.status === 409) {
      return 'Impossible de supprimer cet utilisateur car il est associé à des données.';
    }
    return 'Erreur lors de la suppression de l\'utilisateur. Veuillez réessayer.';
  }

  // ==================== VALIDATION DU FORMULAIRE ====================

  private validateUserForm(): { isValid: boolean; error?: string } {
    const requiredFields = [
      { field: this.newUser.username?.trim(), name: 'Nom d\'utilisateur' },
      { field: this.newUser.email?.trim(), name: 'Email' },
      { field: this.newUser.firstName?.trim(), name: 'Prénom' },
      { field: this.newUser.lastName?.trim(), name: 'Nom' },
      { field: this.selectedMerchantPartnerId?.trim(), name: 'Merchant Partner ID' }
    ];

    for (const { field, name } of requiredFields) {
      if (!field) {
        return { isValid: false, error: `${name} est requis` };
      }
    }

    // Validation email
    const email = this.newUser.email?.trim();
    if (!email) {
      return { isValid: false, error: 'Email est requis' };
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return { isValid: false, error: 'Format d\'email invalide' };
    }

    if (!this.newUser.password || this.newUser.password.length < 8) {
      return { isValid: false, error: 'Le mot de passe doit contenir au moins 8 caractères' };
    }

    if (!this.newUser.role) {
      return { isValid: false, error: 'Le rôle est requis' };
    }

    return { isValid: true };
  }
}