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';

@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;
  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.mode = 'default';
    }

    switch (this.mode) {
      case 'default':
        break;

      case 'forgot-password':
        break;

      default:
        this.mode = 'default'; // กันพลาดไว้เลย
        break;
    }
  }


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

    this.loginForgotComponent.isLoading = true;
    this.generalService.postRequest(uri, request).subscribe({
      next: (result: any) => {
        if (result.code === '200') {
          console.log(`✅ OTP ส่งไปที่ ${value.email}`);
        } else {
          console.warn('⚠️ ไม่สามารถส่ง OTP ได้:', result.message_th);
        }
      },
      error: (error: any) => {
        this.loginForgotComponent.isSendOtp = false;
        this.loginForgotComponent.isLoading = false;
        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 = 'http://49.231.182.24:1012/api/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');
      }
    });
  }
}
