import { Component, OnInit, ViewChild  } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { GeneralService } from '../../services/generalservice';
import { LoginForgotComponent } from '../../../app/component/login-forgot/login-forgot.component';
import { LoginPageComponent } from '../../../app/component/login-page/login-page.component';
import { finalize } from 'rxjs/operators';

@Component({
  selector: 'app-login-content',
  standalone: false,
  templateUrl: './login-content.component.html',
  styleUrl: './login-content.component.css'
})
export class LoginContentComponent implements OnInit {
 @ViewChild(LoginForgotComponent) loginForgotComponent!: LoginForgotComponent;
 @ViewChild(LoginPageComponent) loginPageComponent!: LoginPageComponent;
  mode: 'forgot-password' | 'default' = 'default';

  constructor(
    private generalService: GeneralService,
    private route: ActivatedRoute,
    private router: Router
  ) {}

  ngOnInit(): void {
     let param = this.route.snapshot.paramMap.get('mode');

    if (param === 'forgot-password') {
      this.mode = 'forgot-password';
    } else {
      // this.router.navigate(['/login']); // This can cause navigation loops
      this.mode = 'default';
    }
  }

  onSignInSubmit(value: any){
    const uri = '/api/login/login';
    const request = {
      username: value.username,
      password: value.password
    };

    if (this.loginPageComponent) {
      this.loginPageComponent.busy = true;
      this.loginPageComponent.message = '';
    }

    this.generalService.postRequest(uri, request)
    .pipe(
      finalize(() => {
        if (this.loginPageComponent) {
          this.loginPageComponent.busy = false;
        }
      })
    ).subscribe({
      next: (result: any) => {
        if (result.code === '200' && result.data?.token) {
          this.generalService.trowApi(result);
          localStorage.setItem('access_token', result.data.token);
          this.router.navigate(['main/dashboard']);
        } else {
          const errorMessage = result.message_th || result.message || 'Sign-in failed.';
          if (this.loginPageComponent) {
            this.loginPageComponent.message = errorMessage;
          }
          this.generalService.trowApi(result);
        }
      },
      error: (error: any) => {
        const errorMessage = error?.error?.message_th || error?.error?.message || 'An error occurred.';
        if (this.loginPageComponent) {
          this.loginPageComponent.message = errorMessage;
        }
        this.generalService.trowApi(error);
      }
    });
  }


  onOtpSendSubmit(value: any){
    let uri = '/api/login/otp/send';
    let request = {
      email: value.email
      // otp: value.otp
    }

    this.loginForgotComponent.isLoading = true;
    this.generalService.postRequest(uri, request)
    .pipe(
      // ✅ finalize จะทำงานทุกกรณี (ทั้ง success/error)
      finalize(() => {
        this.loginForgotComponent.isLoading = false;
      })
    ).subscribe({
      next: (result: any) => {
        if (result.code === '200') {
          this.generalService.trowApi(result);
          console.log(`✅ OTP ส่งไปที่ ${value.email}`);
        } else {
          console.warn('⚠️ ไม่สามารถส่ง OTP ได้:', result.message_th);
        }
      },
      error: (error: any) => {
        this.loginForgotComponent.isSendOtp = false;
        this.loginForgotComponent.isLoading = false;
        this.generalService.trowApi(error);
        console.error('❌ Error sending OTP:', error);
      },
      complete: () => {
        this.loginForgotComponent.isLoading = false;
        this.loginForgotComponent.isSendOtp = true;
        console.log('📨 OTP send request completed');
      }
    });
  }

  onVerifySubmit(value: any){
      let uri = '/api/login/otp/verify';
      let request = {
        email: value.email,
        otp: value.otp
    }
    this.generalService.postRequest(uri, request).subscribe({
      next: (result: any) => {
        if (result.code === '200') {
          console.log(`OTP ส่งไปยืนยันสำเร็จ`);
        } else {
          console.warn('⚠️ ไม่สามารถส่ง OTP ได้:', result.message_th);
        }
      },
      error: (error: any) => {
        console.error('❌ Error sending OTP:', error);
      },
      complete: () => {
        this.router.navigate(['/login']);
        console.log('📨 OTP send request completed');
      }
    });
  }
}
