import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators, FormsModule } from '@angular/forms';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { AuthService } from 'app/core/auth/auth.service';
import { RoleStateService } from 'app/core/services/role-state.service';
import { environment } from '@environments/environment';
import { Subject, takeUntil } from 'rxjs';

interface Role {
  id: number;
  name: string;
  description: string;
  permissions: string[];
  created_at: string;
  updated_at: string;
}

interface Permission {
  id: string;
  name: string;
  description: string;
  module: string;
}

@Component({
  selector: 'app-role-management',
  templateUrl: './role-management.component.html',
  styleUrls: ['./role-management.component.scss'],
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule, FormsModule]
})
export class RoleManagementComponent implements OnInit, OnDestroy {
  roles: Role[] = [];
  filteredRoles: Role[] = [];
  roleForm: FormGroup;
  isEditing = false;
  currentRoleId: number | null = null;
  searchTerm = '';
  showAddRoleForm = false;
  isLoading = false;
  errorMessage: string | null = null;
  successMessage: string | null = null;
  
  availablePermissions: Permission[] = [];
  modules: string[] = [];
  permissionMap: { [key: string]: Permission } = {};

  private apiUrl = environment.apiUrl;
  private destroy$ = new Subject<void>();

  constructor(
    private fb: FormBuilder,
    private http: HttpClient,
    private authService: AuthService,
    private roleStateService: RoleStateService
  ) {
    this.roleForm = this.fb.group({
      name: ['', [Validators.required, Validators.minLength(3)]],
      description: [''],
      permissions: [[], Validators.required]
    });
  }

  ngOnInit(): void {
    this.loadPermissions();
    this.loadRoles();
  }

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

  private getHeaders(): HttpHeaders {
    const token = this.authService.accessToken;
    return new HttpHeaders({
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    });
  }

  loadPermissions(): void {
    this.http.get<Permission[]>(`${this.apiUrl}/permissions`, { headers: this.getHeaders() })
      .subscribe({
        next: (permissions) => {
          this.availablePermissions = permissions;
          this.extractModules();
          permissions.forEach(p => {
            this.permissionMap[p.id] = p;
          });
          console.log('✓ Permissions loaded:', permissions.length);
        },
        error: (error) => {
          console.error('Error loading permissions:', error);
          this.showError('Failed to load permissions');
        }
      });
  }

  extractModules(): void {
    this.modules = [...new Set(this.availablePermissions.map(p => p.module))];
  }

  loadRoles(): void {
    this.isLoading = true;
    this.http.get<Role[]>(`${this.apiUrl}/roles`, { headers: this.getHeaders() })
      .subscribe({
        next: (roles) => {
          this.roles = roles;
          this.filteredRoles = [...roles];
          this.isLoading = false;
          console.log('✓ Roles loaded:', roles.length);
        },
        error: (error) => {
          console.error('Error loading roles:', error);
          this.showError('Failed to load roles');
          this.isLoading = false;
        }
      });
  }

  onSearch(): void {
    if (!this.searchTerm.trim()) {
      this.filteredRoles = [...this.roles];
      return;
    }
    
    const searchTermLower = this.searchTerm.toLowerCase();
    this.filteredRoles = this.roles.filter(role => 
      role.name.toLowerCase().includes(searchTermLower) || 
      role.description.toLowerCase().includes(searchTermLower)
    );
  }

  onSubmit(): void {
    if (this.roleForm.invalid) {
      this.showError('Please fill in all required fields correctly');
      return;
    }

    const formValue = this.roleForm.value;
    this.isLoading = true;
    
    if (this.isEditing && this.currentRoleId !== null) {
      // Update existing role
      this.http.put<Role>(
        `${this.apiUrl}/roles/${this.currentRoleId}`,
        formValue,
        { headers: this.getHeaders() }
      ).subscribe({
        next: (updatedRole) => {
          // Update role in local arrays
          const index = this.roles.findIndex(r => r.id === this.currentRoleId);
          if (index !== -1) {
            this.roles[index] = updatedRole;
          }
          
          const filteredIndex = this.filteredRoles.findIndex(r => r.id === this.currentRoleId);
          if (filteredIndex !== -1) {
            this.filteredRoles[filteredIndex] = updatedRole;
          }
          
          // ⭐ Notify other components about role update
          this.roleStateService.notifyRoleUpdate(
            updatedRole.id,
            updatedRole.name,
            updatedRole.permissions
          );
          
          this.showSuccess('Role updated successfully');
          this.resetForm();
          this.showAddRoleForm = false;
          this.isLoading = false;
          
          console.log('✓ Role updated:', updatedRole);
        },
        error: (error) => {
          console.error('Error updating role:', error);
          this.showError(error.error?.error || 'Failed to update role');
          this.isLoading = false;
        }
      });
    } else {
      // Create new role
      this.http.post<Role>(
        `${this.apiUrl}/roles`,
        formValue,
        { headers: this.getHeaders() }
      ).subscribe({
        next: (newRole) => {
          // Add new role to arrays
          this.roles.push(newRole);
          this.filteredRoles = [...this.roles];
          
          // ⭐ Notify other components about new role
          this.roleStateService.notifyRoleCreated(
            newRole.id,
            newRole.name,
            newRole.permissions
          );
          
          this.showSuccess('Role created successfully');
          this.resetForm();
          this.showAddRoleForm = false;
          this.isLoading = false;
          
          console.log('✓ Role created:', newRole);
        },
        error: (error) => {
          console.error('Error creating role:', error);
          this.showError(error.error?.error || 'Failed to create role');
          this.isLoading = false;
        }
      });
    }
  }

  editRole(role: Role): void {
    this.isEditing = true;
    this.currentRoleId = role.id;
    this.roleForm.patchValue({
      name: role.name,
      description: role.description,
      permissions: [...role.permissions]
    });
    this.showAddRoleForm = true;
    
    console.log('Editing role:', role.name, 'Permissions:', role.permissions);
  }

  deleteRole(id: number): void {
    const role = this.roles.find(r => r.id === id);
    if (!role) return;
    
    if (!confirm(`Are you sure you want to delete the "${role.name}" role? This action cannot be undone.`)) {
      return;
    }

    this.isLoading = true;
    this.http.delete(`${this.apiUrl}/roles/${id}`, { headers: this.getHeaders() })
      .subscribe({
        next: () => {
          // Remove from both arrays
          this.roles = this.roles.filter(r => r.id !== id);
          this.filteredRoles = this.filteredRoles.filter(r => r.id !== id);
          
          // ⭐ Notify other components about role deletion
          this.roleStateService.notifyRoleDeleted(id);
          
          this.showSuccess('Role deleted successfully');
          this.isLoading = false;
          
          console.log('✓ Role deleted, ID:', id);
        },
        error: (error) => {
          console.error('Error deleting role:', error);
          this.showError(error.error?.error || 'Failed to delete role');
          this.isLoading = false;
        }
      });
  }

  resetForm(): void {
    this.roleForm.reset({
      name: '',
      description: '',
      permissions: []
    });
    this.isEditing = false;
    this.currentRoleId = null;
  }

  cancelEdit(): void {
    this.resetForm();
    this.showAddRoleForm = false;
  }

  toggleAddRoleForm(): void {
    this.showAddRoleForm = !this.showAddRoleForm;
    if (!this.showAddRoleForm) {
      this.resetForm();
    }
  }

  hasPermission(role: Role, permissionId: string): boolean {
    return role.permissions.includes(permissionId);
  }
  
  toggleAllModulePermissions(module: string, checked: boolean): void {
    const modulePermissionIds = this.availablePermissions
      .filter(p => p.module === module)
      .map(p => p.id);
      
    const currentPermissions = this.roleForm.get('permissions')?.value || [];
    
    if (checked) {
      const newPermissions = [
        ...currentPermissions,
        ...modulePermissionIds.filter(id => !currentPermissions.includes(id))
      ];
      this.roleForm.get('permissions')?.setValue(newPermissions);
    } else {
      const newPermissions = currentPermissions.filter(id => !modulePermissionIds.includes(id));
      this.roleForm.get('permissions')?.setValue(newPermissions);
    }
    
    this.roleForm.get('permissions')?.markAsDirty();
  }
  
  isModuleFullySelected(module: string): boolean {
    const modulePermissionIds = this.availablePermissions
      .filter(p => p.module === module)
      .map(p => p.id);
    
    const currentPermissions = this.roleForm.get('permissions')?.value || [];
    return modulePermissionIds.length > 0 && 
           modulePermissionIds.every(id => currentPermissions.includes(id));
  }
  
  getPermissionsByModule(module: string): Permission[] {
    return this.availablePermissions.filter(p => p.module === module);
  }
  
  getPermissionById(id: string): Permission | undefined {
    return this.permissionMap[id];
  }

  updatePermissions(permissionId: string, isChecked: boolean): void {
    const permissions = [...(this.roleForm.get('permissions')?.value || [])];
    
    if (isChecked && !permissions.includes(permissionId)) {
      permissions.push(permissionId);
    } else if (!isChecked) {
      const index = permissions.indexOf(permissionId);
      if (index !== -1) {
        permissions.splice(index, 1);
      }
    }
    
    this.roleForm.get('permissions')?.setValue(permissions);
    this.roleForm.get('permissions')?.markAsDirty();
  }

  /**
   * ⭐ Toggle permission in the table with immediate local update
   */
  togglePermission(role: Role, permissionId: string, checked: boolean): void {
    console.log(`Toggling permission: ${permissionId} for role: ${role.name}, checked: ${checked}`);
    
    // Create updated permissions array
    const updatedPermissions = [...role.permissions];
    
    if (checked) {
      if (!updatedPermissions.includes(permissionId)) {
        updatedPermissions.push(permissionId);
      }
    } else {
      const index = updatedPermissions.indexOf(permissionId);
      if (index !== -1) {
        updatedPermissions.splice(index, 1);
      }
    }
    
    // ⭐ IMMEDIATELY update local state for instant UI feedback
    const roleIndex = this.roles.findIndex(r => r.id === role.id);
    if (roleIndex !== -1) {
      this.roles[roleIndex] = {
        ...this.roles[roleIndex],
        permissions: updatedPermissions
      };
    }
    
    const filteredIndex = this.filteredRoles.findIndex(r => r.id === role.id);
    if (filteredIndex !== -1) {
      this.filteredRoles[filteredIndex] = {
        ...this.filteredRoles[filteredIndex],
        permissions: updatedPermissions
      };
    }
    
    // Update backend
    this.http.put<Role>(
      `${this.apiUrl}/roles/${role.id}`,
      { permissions: updatedPermissions },
      { headers: this.getHeaders() }
    ).subscribe({
      next: (updatedRole) => {
        console.log('✓ Permission updated on backend:', updatedRole);
        
        // Update with backend response
        const roleIdx = this.roles.findIndex(r => r.id === role.id);
        if (roleIdx !== -1) {
          this.roles[roleIdx] = updatedRole;
        }
        
        const filteredIdx = this.filteredRoles.findIndex(r => r.id === role.id);
        if (filteredIdx !== -1) {
          this.filteredRoles[filteredIdx] = updatedRole;
        }
        
        // ⭐ Notify other components about permission change
        this.roleStateService.notifyRoleUpdate(
          updatedRole.id,
          updatedRole.name,
          updatedRole.permissions
        );
      },
      error: (error) => {
        console.error('Error updating permissions:', error);
        this.showError('Failed to update permissions');
        
        // Rollback on error
        this.loadRoles();
      }
    });
  }

  private showSuccess(message: string): void {
    this.successMessage = message;
    this.errorMessage = null;
    setTimeout(() => this.successMessage = null, 3000);
  }

  private showError(message: string): void {
    this.errorMessage = message;
    this.successMessage = null;
    setTimeout(() => this.errorMessage = null, 5000);
  }
}