import { Component, ChangeDetectorRef } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Router, RouterModule } from '@angular/router';
import { AuthService } from '../../services/auth.service';
import { UserService } from '../../services/user.service';
import { LoggerService } from '../../services/logger.service';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [CommonModule, FormsModule, RouterModule],
  templateUrl: './login.component.html',
  styleUrl: './login.component.scss'
})
export class LoginComponent {
  email = '';
  password = '';
  code = ''; // 2FA code
  error: string | null = null;
  loading = false;
  requires2FA = false;
  showPassword = false;
  rememberMe = false;
  emailError = '';
  passwordError = '';

  constructor(
    private auth: AuthService, 
    private userService: UserService, 
    private router: Router,
    private cdr: ChangeDetectorRef,
    private logger: LoggerService
  ) {}

  validateEmail() {
    this.emailError = '';
    if (!this.email) {
      return;
    }
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(this.email)) {
      this.emailError = 'Please enter a valid email address';
    }
  }

  validatePassword() {
    this.passwordError = '';
    if (!this.password) {
      return;
    }
    if (this.password.length < 3) {
      this.passwordError = 'Password is too short';
    }
  }

  async submit() {
    this.error = null;
    this.emailError = '';
    this.passwordError = '';

    // Validation
    if (!this.email) {
      this.emailError = 'Email is required';
      return;
    }
    this.validateEmail();
    if (this.emailError) {
      return;
    }

    if (!this.requires2FA && !this.password) {
      this.passwordError = 'Password is required';
      return;
    }
    if (!this.requires2FA) {
      this.validatePassword();
      if (this.passwordError) {
        return;
      }
    }

    if (this.requires2FA && !this.code) {
      this.error = 'Please enter your 2FA code';
      return;
    }

    this.loading = true;
    try {
      const result = await this.auth.login(this.email, this.password, this.code || undefined);
      
      if (result.requires2FA) {
        this.logger.debug('Result indicates 2FA required, setting requires2FA to true');
        this.requires2FA = true;
        this.error = null;
        // Clear the code when switching to 2FA mode
        this.code = '';
        // Force change detection to update the view
        this.cdr.detectChanges();
        // Use requestAnimationFrame to ensure DOM is updated
        requestAnimationFrame(() => {
          const codeInput = document.getElementById('code');
          if (codeInput) {
            codeInput.focus();
          }
        });
      } else if (result.token) {
        // Get user info to determine role-based redirect
        const user = await this.userService.getCurrentUser();
        if (user) {
          if (user.role === 'ADMIN') {
            this.router.navigateByUrl('/admin');
          } else if (user.role === 'DOCTOR') {
            this.router.navigateByUrl('/doctor');
          } else if (user.role === 'PATIENT') {
            this.router.navigateByUrl('/patient');
          } else {
            this.router.navigateByUrl('/admin');
          }
        } else {
          this.router.navigateByUrl('/admin');
        }
      }
    } catch (e: any) {
      const errorMessage = (e?.response?.data?.message || e?.response?.data?.error || '').toLowerCase();
      const statusCode = e?.response?.status;
      
      this.logger.debug('Login component error:', { 
        status: statusCode, 
        message: e?.response?.data?.message || e?.response?.data?.error,
        requires2FA: this.requires2FA,
        fullError: e?.response?.data 
      });
      
      // If we're in 2FA mode and got an error
      if (this.requires2FA) {
        // If it's an invalid 2FA code error, keep requires2FA true
        if (errorMessage.includes('invalid 2fa') || errorMessage.includes('2fa code')) {
          this.error = 'Invalid 2FA code. Please try again.';
          this.code = ''; // Clear the code input
          // Keep requires2FA = true
        } else {
          // Some other error - might be wrong credentials, reset 2FA
          this.error = e?.response?.data?.message || e?.response?.data?.error || 'Login failed. Please try again.';
          this.requires2FA = false;
          this.code = '';
          this.password = ''; // Clear password on error
        }
      } else {
        // Not in 2FA mode - check if 2FA is required
        // Check for "2FA code required" message or 400 status with 2FA in message
        const is2FARequired = errorMessage.includes('2fa code required') || 
                              (statusCode === 400 && errorMessage.includes('2fa') && !errorMessage.includes('invalid'));
        
        if (is2FARequired) {
          this.logger.debug('Setting requires2FA to true');
          this.requires2FA = true;
          this.error = null;
          // Don't clear password - user needs it for the next step
          // Force change detection to update the view
          this.cdr.detectChanges();
          // Use requestAnimationFrame to ensure DOM is updated
          requestAnimationFrame(() => {
            const codeInput = document.getElementById('code');
            if (codeInput) {
              codeInput.focus();
            }
          });
        } else {
          // Regular login error
          this.error = e?.response?.data?.message || e?.response?.data?.error || 'Login failed. Please check your credentials.';
        }
      }
    } finally {
      this.loading = false;
    }
  }

  togglePasswordVisibility() {
    this.showPassword = !this.showPassword;
  }

  reset2FA() {
    this.requires2FA = false;
    this.code = '';
    this.error = null;
  }
}
