import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { filter, debounceTime, distinctUntilChanged, switchMap, catchError } from 'rxjs/operators';
import { of, Subject } from 'rxjs';
import { Router } from '@angular/router';
import { HeaderComponent } from '../header/header.component';

@Component({
  selector: 'app-signup',
  standalone: true,
  imports: [ReactiveFormsModule, CommonModule, HeaderComponent],
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.css'],
})
export class SignupComponent {
  signupForm: FormGroup;
  mobileStatus: 'available' | 'taken' | 'checking' | null = null;
  submissionErrors: string[] = [];
  isCheckingMobile = false;
  message: string = '';
  isSubmitting: boolean = false;
  showOtpField: boolean = false;
  otpSent: boolean = false;
  countdown: number = 0;
  countdownInterval: any;
  private mobileCheckSubject = new Subject<string>();

  constructor(private fb: FormBuilder, private http: HttpClient, private router: Router) {
    this.signupForm = this.fb.group({
      first_name: ['', [Validators.required]],
      mobile: ['', [Validators.required, Validators.pattern(/^[0-9]{10}$/)]],
      otp: [''],
      terms: [false, [Validators.requiredTrue]],
    });

    // Setup mobile check subscription
    this.setupMobileCheck();
  }

  setupMobileCheck() {
    this.mobileCheckSubject.pipe(
      debounceTime(800),
      distinctUntilChanged(),
      filter(mobile => {
        const isValid = this.signupForm.get('mobile')?.valid || false;
        if (!isValid) {
          this.mobileStatus = null;
          return false;
        }
        return true;
      }),
      switchMap(mobile => {
        this.mobileStatus = 'checking';
        this.isCheckingMobile = true;
        return this.checkMobile(mobile).pipe(
          catchError((error) => {
            this.isCheckingMobile = false;
            this.mobileStatus = null;
            console.error('Mobile check error:', error);
            return of({ exists: false, error: true });
          })
        );
      })
    ).subscribe(res => {
      this.isCheckingMobile = false;
      if (res.error) {
        this.mobileStatus = null;
        return;
      }
      this.mobileStatus = res.exists ? 'taken' : 'available';
    });

    // Subscribe to mobile value changes
    this.signupForm.get('mobile')?.valueChanges.subscribe(mobile => {
      this.mobileCheckSubject.next(mobile);
    });
  }

  sendOtp() {
    // Reset previous messages
    this.submissionErrors = [];
    this.message = '';
    
    const mobile = this.signupForm.get('mobile')?.value;
    if (!mobile || this.signupForm.get('mobile')?.invalid) {
      this.submissionErrors = ['Please enter a valid mobile number'];
      return;
    }
    
    // Check if mobile is already taken before sending OTP
    if (this.mobileStatus === 'taken') {
      this.submissionErrors = ['Mobile number already registered'];
      return;
    }

    this.isSubmitting = true;
    const formData = {
      mobile: mobile,
      send_otp: true
    };

    const headers = new HttpHeaders({
      'content-type': 'application/json',
    });

    this.http.post(
      'https://infoways.in/funtelapi/signup.php',
      JSON.stringify(formData),
      { headers, withCredentials: true }
    ).subscribe({
      next: (res: any) => {
        this.isSubmitting = false;
        if (res.status === 'success') {
          this.otpSent = true;
          this.showOtpField = true;
          this.startCountdown(120); // 2 minutes countdown
          this.message = 'OTP sent to your mobile number';
        } else {
          this.submissionErrors = [res.message || 'Failed to send OTP'];
        }
      },
      error: (err) => {
        this.isSubmitting = false;
        console.error('OTP error:', err);
        this.submissionErrors = ['Failed to send OTP. Please try again.'];
      }
    });
  }

  startCountdown(seconds: number) {
    this.countdown = seconds;
    this.countdownInterval = setInterval(() => {
      this.countdown--;
      if (this.countdown <= 0) {
        clearInterval(this.countdownInterval);
        this.otpSent = false;
      }
    }, 1000);
  }

  onSubmit() {
    this.submissionErrors = [];
    this.message = '';
    this.isSubmitting = true;

    if (this.signupForm.invalid || this.mobileStatus === 'taken') {
      if (this.signupForm.get('first_name')?.invalid) {
        this.submissionErrors.push('Full name is required');
      }
      if (this.signupForm.get('mobile')?.invalid) {
        this.submissionErrors.push('Valid 10-digit mobile number is required');
      }
      if (this.mobileStatus === 'taken') {
        this.submissionErrors.push('Mobile number already exists');
      }
      if (this.showOtpField && !this.signupForm.get('otp')?.value) {
        this.submissionErrors.push('OTP is required');
      }
      if (!this.signupForm.get('terms')?.value) {
        this.submissionErrors.push('Please accept Terms and Conditions');
      }
      this.isSubmitting = false;
      return;
    }

    const formData = {
      first_name: this.signupForm.value.first_name,
      mobile: this.signupForm.value.mobile,
      otp: this.signupForm.value.otp || ''
    };

    const headers = new HttpHeaders({
      'content-type': 'application/json',
    });

    this.http.post(
      'https://infoways.in/funtelapi/signup.php',
      JSON.stringify(formData),
      { headers, withCredentials: true }
    ).subscribe({
      next: (res: any) => {
        this.isSubmitting = false;
        if (res.status === 'success') {
          this.message = '✅ Signup successful! Your account has been created.';
          this.signupForm.reset();
          this.mobileStatus = null;
          this.showOtpField = false;
          this.otpSent = false;
          clearInterval(this.countdownInterval);
          
          // Redirect to login after 3 seconds
          setTimeout(() => {
            this.router.navigate(['/login']);
          }, 3000);
        } else {
          this.submissionErrors = [res.message || 'Signup completed but with unexpected response'];
        }
      },
      error: (err) => {
        this.isSubmitting = false;
        console.error('Signup error:', err);
        try {
          if (err.error && err.error.message) {
            this.submissionErrors = [err.error.message];
          } else {
            this.submissionErrors = ['Signup failed. Please try again.'];
          }
        } catch (e) {
          this.submissionErrors = ['Signup failed. Please try again.'];
        }
      }
    });
  }

  checkMobile(mobile: string) {
    return this.http.post<any>(
      'https://infoways.in/funtelapi/signup.php', 
      JSON.stringify({ check_mobile: true, mobile }),
      {
        headers: new HttpHeaders({
          'Content-Type': 'application/json'
        }),
        withCredentials: true
      }
    );
  }

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