import { Component } from '@angular/core';
import {MatButtonModule} from '@angular/material/button';
import { AuthService } from '../auth.service';
import { Router } from '@angular/router';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { HeaderComponent } from '../header/header.component';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule, FormsModule, HeaderComponent],
  templateUrl: './login.component.html',
  styleUrl: './login.component.css'
})
export class LoginComponent {
  isOtpSent: boolean = false;
  showRegistrationFields: boolean = false;
  countdown: number = 0;
  countdownInterval: any;
  errorMessage: string = '';
  successMessage: string = '';
  isNewUser: boolean = false;
  userExists:boolean = false;
  
  loginForm = this.fb.group({
    mobile: ['', [Validators.required, Validators.pattern('^[0-9]{10}$')]],
    otp: ['', [Validators.minLength(6), Validators.maxLength(6)]],
    first_name: ['', [Validators.required]],
    last_name: [''],
    email: ['', [Validators.email]]
  });

  constructor(
    private authService: AuthService, 
    private router: Router,  
    private fb: FormBuilder
  ) {}

  ngOnInit() {
    // Check if already logged in via cookie
    // this.authService.isLoggedIn().subscribe(isLoggedIn => {
    //   if (isLoggedIn) {
    //     this.router.navigate(['/home']);
    //   }
    // });
  }

  sendOtp() {
  if (this.loginForm.get('mobile')?.valid) {
    const mobile = this.loginForm.get('mobile')?.value as string;
    
    this.authService.sendOtp(mobile).subscribe({
      next: (response: any) => {
        if (response.status === 'success') {
          this.isOtpSent = true;
          this.successMessage = 'OTP sent to your mobile number';
          
          // Store whether user exists or not
          this.userExists = response.userExists;
          
          // For development, show OTP if it's in the response
          // if (response.otp) {
          //   this.successMessage += `. Development OTP: ${response.otp}`;
          //   console.log('OTP for development:', response.otp);
          // }
          
          this.errorMessage = '';
          this.startCountdown();
        } else {
          this.errorMessage = response.error || 'Failed to send OTP';
          this.successMessage = '';
        }
      },
      error: (err) => {
        this.errorMessage = err.error?.error || 'Server error occurred';
        this.successMessage = '';
        console.error('OTP send error:', err);
      }
    });
  }
}

  verifyOtp() {
  if (this.loginForm.get('otp')?.valid) {
    const mobile = this.loginForm.get('mobile')?.value as string;
    const otp = this.loginForm.get('otp')?.value as string;
    
    this.authService.verifyOtp(mobile, otp).subscribe({
      next: (response) => {
        if (response.status === 'success') {
          if (response.userExists) {
            // Existing user - login karein
            if (response.isAdmin) {
              this.router.navigate(['/dashboard']);
            } else {
              this.router.navigate(['/new']);
            }
          } else {
            // New user - registration fields show karein
            this.showRegistrationFields = true;
            this.isNewUser = true;
            this.successMessage = 'Please complete your registration';
          }
        } else {
          this.errorMessage = response.error || 'Invalid OTP';
        }
      },
      error: (err) => {
        this.errorMessage = err.error?.error || 'Server error occurred';
        console.error(err);
      }
    });
  }
}

completeRegistration() {
  console.log('Complete Registration called');
  console.log('Form valid:', this.loginForm.valid);
  console.log('Form values:', this.loginForm.value);
  
  if (this.loginForm.valid) {
    const formData = {
      mobile: this.loginForm.get('mobile')?.value,
      first_name: this.loginForm.get('first_name')?.value,
      last_name: this.loginForm.get('last_name')?.value,
      email: this.loginForm.get('email')?.value
    };
    
    console.log('Sending data to server:', formData);
    
    this.authService.registerNewUser(formData).subscribe({
      next: (response: any) => {
        console.log('Server response:', response);
        if (response.status === 'success') {
          this.router.navigate(['/home']);
        } else {
          this.errorMessage = response.error || 'Registration failed';
        }
      },
      error: (err) => {
        console.error('Registration error:', err);
        this.errorMessage = err.error?.error || 'Server error occurred';
      }
    });
  } else {
    console.log('Form is invalid');
    // Mark all fields as touched to show validation errors
    this.loginForm.markAllAsTouched();
  }
}

  startCountdown() {
    this.countdown = 60;
    this.countdownInterval = setInterval(() => {
      this.countdown--;
      if (this.countdown <= 0) {
        clearInterval(this.countdownInterval);
      }
    }, 1000);
  }

  resendOtp() {
    if (this.countdown <= 0) {
      this.sendOtp();
    }
  }

  ngOnDestroy() {
    if (this.countdownInterval) {
      clearInterval(this.countdownInterval);
    }
  }
}