import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { IndicatorsModule } from '@progress/kendo-angular-indicators';
import { ButtonsModule } from '@progress/kendo-angular-buttons';
import { DialogModule } from '@progress/kendo-angular-dialog';
import { AuthService, TokenVerificationResult, UserInfo } from '../services/auth.service';
import { MfaDialogComponent } from '../mfa-dialog/mfa-dialog.component';

@Component({
    selector: 'app-token-verification',
    standalone: true,
    imports: [
        CommonModule,
        IndicatorsModule,
        ButtonsModule,
        DialogModule,
        MfaDialogComponent
    ],
    templateUrl: './token-verification.component.html',
    styleUrls: ['./token-verification.component.scss']
})
export class TokenVerificationComponent implements OnInit, AfterViewInit {
    @ViewChild('mfaDialog') mfaDialog!: MfaDialogComponent;

    isVerifying = true;
    verificationResult: TokenVerificationResult | null = null;
    errorMessage = '';
    tokenUser: UserInfo | null = null;

    constructor(
        private route: ActivatedRoute,
        private router: Router,
        private authService: AuthService
    ) { }

    ngOnInit(): void {
        this.route.queryParams.subscribe(params => {
            const token = params['token'];
            if (token) {
                this.verifyToken(token);
            } else {
                this.handleError('No token provided in the link');
            }
        });
    }

    ngAfterViewInit(): void {
        console.log('AfterViewInit - MFA dialog reference:', this.mfaDialog);
    }

    private verifyToken(token: string): void {
        this.isVerifying = true;
        this.errorMessage = '';

        // Validate token format first
        if (!this.isValidJwtFormat(token)) {
            this.handleError('Invalid token format. Please check your email link.');
            return;
        }

        this.authService.verifySecretLinkToken(token).subscribe({
            next: (result: TokenVerificationResult) => {
                this.isVerifying = false;
                this.verificationResult = result;

                if (result.isValid && result.user) {
                    // Token is valid, store user data and show MFA dialog
                    this.tokenUser = result.user;
                    this.verificationResult = result;

                    console.log('Token verification result:', result);
                    console.log('Requires MFA:', result.requiresMfa);

                    if (result.requiresMfa) {
                        // Show MFA dialog for token-based authentication
                        console.log('Showing MFA dialog...');
                        this.showMfaDialog();
                    } else {
                        // If MFA is not required, proceed directly
                        console.log('MFA not required, proceeding directly...');
                        this.authService.setCurrentUser(result.user);
                        setTimeout(() => {
                            this.redirectToDashboard();
                        }, 2000);
                    }
                } else {
                    this.handleError(result.message || 'Invalid or expired link. Please request a new one.');
                }
            },
            error: (error) => {
                this.isVerifying = false;
                this.handleError('An error occurred while verifying the link. Please try again.');
                console.error('Token verification error:', error);
            }
        });
    }

    private isValidJwtFormat(token: string): boolean {
        // Basic JWT format validation (3 parts separated by dots)
        const parts = token.split('.');
        return parts.length === 3 && parts.every(part => part.length > 0);
    }

    private handleError(message: string): void {
        this.isVerifying = false;
        this.errorMessage = message;
    }

    private redirectToDashboard(): void {
        const redirectUrl = this.authService.getRedirectUrl();
        this.router.navigate([redirectUrl || '/dashboard']);
    }

    goToLogin(): void {
        this.router.navigate(['/login']);
    }

    requestNewLink(): void {
        // This could redirect to a "request new link" page or contact form
        // For now, redirect to login
        this.router.navigate(['/login']);
    }

    showMfaDialog(): void {
        console.log('showMfaDialog called, tokenUser:', this.tokenUser);

        if (this.tokenUser) {
            // Set the user data for MFA dialog first
            const loginData = {
                email: this.tokenUser.email,
                password: '', // Not needed for token-based auth
                tokenUser: this.tokenUser
            };

            // Use multiple approaches to ensure the dialog shows
            const tryShowDialog = (attempt: number = 1) => {
                console.log(`Attempt ${attempt} to show MFA dialog`);

                if (this.mfaDialog) {
                    console.log('MFA dialog found, setting loginData and showing...');
                    (this.mfaDialog as any).loginData = loginData;
                    this.mfaDialog.show();
                } else if (attempt < 5) {
                    // Try again after a short delay
                    setTimeout(() => tryShowDialog(attempt + 1), 100);
                } else {
                    console.error('MFA dialog not found after multiple attempts');
                }
            };

            // Start trying to show the dialog
            tryShowDialog();
        } else {
            console.error('No token user available for MFA dialog');
        }
    }

    onMfaSuccess(userData: any): void {
        this.authService.setCurrentUser(userData);
        this.redirectToDashboard();
    }

    onMfaCancel(): void {
        // Reset to initial state
        this.isVerifying = true;
        this.verificationResult = null;
        this.tokenUser = null;
        this.errorMessage = '';
    }
}
