import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { TwoFactorAuthService, TwoFactorStatus, TwoFactorSetupResponse } from '../../../../services/two-factor-auth.service';
import { ModalService } from '../../../../services/modal.service';
import { LoggerService } from '../../../../services/logger.service';

@Component({
  selector: 'app-security',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './security.component.html',
  styleUrl: './security.component.scss'
})
export class SecurityComponent implements OnInit {
  @Input() twoFAEnabled = false;
  @Input() twoFAStatus: TwoFactorStatus | null = null;
  @Output() setup2FA = new EventEmitter<void>();
  @Output() disable2FA = new EventEmitter<string>();

  // 2FA Modal State
  show2FAModal = false;
  qrCodeUrl: string = '';
  twoFASecretKey: string = '';
  twoFABackupCodes: string[] = [];
  twoFACodeInput: string = '';
  error: string | null = null;
  loading = false;
  showBackupCodes = false;
  copiedSecretKey = false;
  copiedBackupCodes = false;

  constructor(
    private twoFactorAuthService: TwoFactorAuthService,
    private modalService: ModalService,
    private logger: LoggerService
  ) {}

  ngOnInit() {
    // Component is initialized with inputs from parent
  }

  async onSetup2FA() {
    try {
      this.loading = true;
      this.error = null;
      const setup: TwoFactorSetupResponse = await this.twoFactorAuthService.setup2FA();
      this.qrCodeUrl = setup.qrCodeUrl;
      this.twoFASecretKey = setup.secretKey;
      this.twoFABackupCodes = setup.backupCodes || [];
      this.twoFACodeInput = '';
      this.show2FAModal = true;
      this.showBackupCodes = false;
    } catch (e: any) {
      this.error = e?.response?.data?.error || 'Failed to setup 2FA';
      this.logger.error('Error setting up 2FA:', e);
    } finally {
      this.loading = false;
    }
  }

  async verifyAndEnable2FA() {
    if (!this.twoFACodeInput || this.twoFACodeInput.length !== 6) {
      this.error = 'Please enter a valid 6-digit code';
      return;
    }
    try {
      this.loading = true;
      this.error = null;
      await this.twoFactorAuthService.enable2FA(this.twoFACodeInput);
      await this.refresh2FAStatus();
      this.show2FAModal = false;
      this.showBackupCodes = true;
      // Show success message
      setTimeout(async () => {
        await this.modalService.alert(
          '2FA enabled successfully! Please save your backup codes.',
          'success',
          '2FA Enabled'
        );
      }, 100);
    } catch (e: any) {
      this.error = e?.response?.data?.error || 'Failed to enable 2FA';
      this.logger.error('Error enabling 2FA:', e);
    } finally {
      this.loading = false;
    }
  }

  close2FAModal() {
    this.show2FAModal = false;
    this.qrCodeUrl = '';
    this.twoFASecretKey = '';
    this.twoFABackupCodes = [];
    this.twoFACodeInput = '';
    this.error = null;
    this.showBackupCodes = false;
    this.copiedSecretKey = false;
    this.copiedBackupCodes = false;
  }

  async onDisable2FA() {
    const code = await this.modalService.prompt(
      'Enter your 2FA code or backup code to disable two-factor authentication:',
      'Disable 2FA',
      '2FA Code',
      'Enter 2FA code or backup code',
      'text',
      'Disable',
      'Cancel'
    );
    if (!code) return;
    try {
      this.loading = true;
      this.error = null;
      await this.twoFactorAuthService.disable2FA(code);
      await this.refresh2FAStatus();
      this.disable2FA.emit(code);
      await this.modalService.alert(
        '2FA disabled successfully',
        'success',
        '2FA Disabled'
      );
    } catch (e: any) {
      this.error = e?.response?.data?.error || 'Failed to disable 2FA';
      await this.modalService.alert(
        this.error || 'Failed to disable 2FA',
        'error',
        '2FA Error'
      );
    } finally {
      this.loading = false;
    }
  }

  async refresh2FAStatus() {
    try {
      const status = await this.twoFactorAuthService.get2FAStatus();
      this.twoFAEnabled = status.enabled;
      this.twoFAStatus = status;
      this.setup2FA.emit(); // Notify parent to refresh
    } catch (e: any) {
      this.logger.error('Error refreshing 2FA status:', e);
    }
  }

  copySecretKey() {
    if (this.twoFASecretKey) {
      navigator.clipboard.writeText(this.twoFASecretKey).then(() => {
        this.copiedSecretKey = true;
        setTimeout(() => {
          this.copiedSecretKey = false;
        }, 2000);
      });
    }
  }

  copyBackupCodes() {
    if (this.twoFABackupCodes.length > 0) {
      navigator.clipboard.writeText(this.twoFABackupCodes.join('\n')).then(() => {
        this.copiedBackupCodes = true;
        setTimeout(() => {
          this.copiedBackupCodes = false;
        }, 2000);
      });
    }
  }

  downloadBackupCodes() {
    const content = this.twoFABackupCodes.join('\n');
    const blob = new Blob([content], { type: 'text/plain' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = '2fa-backup-codes.txt';
    link.click();
    window.URL.revokeObjectURL(url);
  }

  onCodeInputChange() {
    // Auto-verify if 6 digits entered
    if (this.twoFACodeInput.length === 6 && /^\d{6}$/.test(this.twoFACodeInput)) {
      // Optional: auto-verify on 6 digits
    }
  }
}
