import { Component, OnInit, AfterViewInit } from '@angular/core';
import { AbstractControl, UntypedFormBuilder, UntypedFormGroup, ValidationErrors, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';

import { AuthenticationService } from '../../../core/services/auth.service';
import { environment } from '../../../../environments/environment';
import { first } from 'rxjs/operators';
import { UserProfileService } from '../../../core/services/user.service';
import { BaseService } from 'src/app/shared/service/base.service';
import { ToastService } from 'src/app/toast/toast-service';
import { v4 as uuidv4 } from 'uuid';


@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.scss']
})
export class SignupComponent implements OnInit, AfterViewInit {

  signupForm: UntypedFormGroup;
  submitted = false;
  error = '';
  successmsg = false;

  passwordVisible = false;

  passwordValid: boolean = false;
  reRetypepasswordVisible:boolean=false;
  RetypepasswordValid: boolean = false;
  showPasswordTooltip: boolean = false;
  passwordLengthValid: boolean = false;
  passwordUpperCaseValid: boolean = false;
  passwordLowerCaseValid: boolean = false;
  passwordNumberValid: boolean = false;
  passwordSpecialCharValid: boolean = false;

  termsAndConditionsAccepted: boolean = false;

  // siteKey = '6Ldg9GIqAAAAALNtDu8nWSQLZEVmB4Wwcyt0d2P_';
  public siteKey: string = '6Ldg9GIqAAAAALNtDu8nWSQLZEVmB4Wwcyt0d2P_';  // replace with your site key
  captchaValid: boolean = false;


  // set the currenr year
  year: number = new Date().getFullYear();

  // tslint:disable-next-line: max-line-length
  constructor(private formBuilder: UntypedFormBuilder, 
    private route: ActivatedRoute, 
    private router: Router, 
    private authenticationService: AuthenticationService,
    // private userService: UserProfileService,
    public baseService: BaseService,
    private toastService: ToastService
  ) { }

  ngOnInit() {
    document.body.setAttribute('class', 'authentication-bg');

    this.signupForm = this.formBuilder.group({
      username: ['', Validators.required],
      lastname:['', Validators.required],
      firstname:['', Validators.required],
      re_type_pass:['', Validators.required],
      email: ['', [Validators.required, Validators.email]],
      password: ['', Validators.required,this.passwordValidator.bind(this)],
    });
  }
  passwordValidator(control: AbstractControl): Promise<ValidationErrors | null> {
    return new Promise((resolve, reject) => {
      // Your validation logic here
      if (control.value && control.value.length < 8) {
        resolve({ minlength: true });
      } else if (!/[A-Z]/.test(control.value)) {
        resolve({ uppercase: true });
      } else if (!/[a-z]/.test(control.value)) {
        resolve({ lowercase: true });
      } else if (!/\d/.test(control.value)) {
        resolve({ number: true });
      } else if (!/[!@#$%^&*(),.?":{}|<>]/.test(control.value)) {
        resolve({ specialCharacter: true });
      } else {
        resolve(null);
      }
    });
  }

  onCaptchaResolved(captchaResponse: string) {
    console.log(`Resolved captcha with response: ${captchaResponse}`);
   
    // Handle reCAPTCHA token and pass it to your backend for validation.

    if (captchaResponse) {

      this.captchaValid = true;

      const formData = new URLSearchParams();

      // Add the reCAPTCHA token to form data
      formData.append('recaptchaToken', captchaResponse);
  
      this.baseService.postData('auth/validateRecaptcha', formData).subscribe(
        (data: any) => {
          if (data) {
            console.log(data);
          }
        },
        (err) => {
          console.error(err);
          const errorMessage = err?.error?.message || 'Register unsuccessfully. Please check required fields!';
        }
      );
    } else {
      // Handle case where reCAPTCHA token is not available
      this.toastService.show('Please complete the reCAPTCHA.', { classname: 'bg-warning text-light', delay: 3000 });
    }
  }

  ngAfterViewInit() {
  }

  ngOnDestroy() { 
    document.body.classList.remove('authentication-bg')
  }

  // convenience getter for easy access to form fields
  get f() { return this.signupForm.controls; }

  get emailControl() {
    return this.signupForm.get('email'); // Access the email control
  }

  get userControl(){
    return this.signupForm.get('username'); 
  }
  get passwordControl(){
    return this.signupForm.get('password'); 
  }
  get lastnameControl(){
    return this.signupForm.get('lastname'); 
  }
  get firstnameControl(){
    return this.signupForm.get('firstname'); 
  }
  get re_type_passControl(){
    return this.signupForm.get('re_type_pass'); 
  }

  

  /**
   * On submit form
   */
  onSubmit() {
    this.submitted = true;

    // Check if reCAPTCHA is valid
    if (!this.captchaValid) {
      alert('Please verify the captcha!');
      return;
    }


    // stop here if form is invalid
    if (this.signupForm.invalid) {
      return;
    } else {
      if (!this.termsAndConditionsAccepted) { // Check if terms and conditions are accepted
        this.error = 'Please accept the terms and conditions.';
        return;
      }
      if (environment.defaultauth === 'firebase') {
        this.authenticationService.register(this.f.email.value, this.f.password.value).then((res: any) => {
          this.successmsg = true;
          if (this.successmsg) {
            document.body.removeAttribute('class');
            this.router.navigate(['/']);
          }
        })
          .catch(error => {
            this.error = error ? error : '';
          });
      } else {
        // this.userService.register(this.signupForm.value)
        //   .pipe(first())
        //   .subscribe(
        //     data => {
        //       this.successmsg = true;
        //       if (this.successmsg) {
        //         this.router.navigate(['/account/login']);
        //       }
        //     },
        //     error => {
        //       this.error = error ? error : '';
        //     });
        const formData = new URLSearchParams();
        formData.append('email', this.signupForm.get('email').value);
        formData.append('username', this.signupForm.get('username').value);
        formData.append('name', this.signupForm.get('firstname').value);

        formData.append('lastName', this.signupForm.get('lastname').value);
        formData.append('password', this.signupForm.get('password').value);

        this.baseService.postData('user/addUserNew', formData).subscribe(
          (data: any) => {
            if (data) {
            console.log(data);
            this.router.navigate(['/account/login']);
            this.toastService.show('Register successfully!', { classname: 'bg-success text-light', delay: 3000 });
            this.AddTenant(data)
            }
          },
          (err) => {
            console.log(err);
            this.toastService.show('Register unsuccessfully please check required field!', { classname: 'bg-error text-light', delay: 3000 });
          }
          );
      }
    }
  }

  AddTenant(data){
    const userid = data.UserID;
    const formData = new URLSearchParams();
      formData.append('tenantUUID', uuidv4());
      formData.append('name', this.signupForm.get('firstname').value);
      formData.append('primaryEmail', this.signupForm.get('email').value);userid
      formData.append('userid', userid);
      this.baseService.postData('tenants/saveTenantNew', formData).subscribe(
        (data: any) => {
          if (data) {
            console.log(data);
            this.addSubscription(data)
          }
        },
        (err) => {
          console.log(err);
        }
      );
  }

  addSubscription(data){
    const tenantUUID = data.data.tenantUUID;
  
    this.baseService.getData(`admin/getAccountDetailByTenant/${tenantUUID}`).subscribe(
      (data: any) => {
        if (data) {
          console.log(data);
          const acccountuuid = data.data.accountUUID;
          const formData = new URLSearchParams();
  
          const startDate = new Date();
          const endDate = new Date();
          endDate.setMonth(startDate.getMonth() + 1);

          // Utility function to format date as YYYY-MM-DD
          const formatDate = (date: Date): string => {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
          };
  
          formData.append('subscriptionuuid', uuidv4());
          formData.append('planid', '1');
          formData.append('tenantuuid', tenantUUID);
          formData.append('acccountuuid', acccountuuid);
          formData.append('isfree', 'true');
          formData.append('iscustom', 'false');
          formData.append('iscancelled', 'false');
          formData.append('startson', formatDate(startDate));
          formData.append('ends_at', formatDate(endDate));
          formData.append('currency', 'USD');
          formData.append('createdon', formatDate(startDate));
  
          this.baseService.postData('subscriptions/subscription', formData).subscribe(
            (data: any) => {
              if (data) {
                console.log(data);
              }
            },
            (err) => {
              console.log(err);
            }
          );
        }
      },
      (err) => {
        console.log(err);
      }
    );
  }

  togglePasswordVisibility() {
    this.passwordVisible = !this.passwordVisible;
  }

  toggleReTypePasswordVisibility() {
    this.reRetypepasswordVisible = !this.reRetypepasswordVisible;
  }

  checkRetypePassword(){
    const password = this.signupForm.get('password').value;
    const repassword = this.signupForm.get('re_type_pass').value;
    this.RetypepasswordValid =  password === repassword;
  }

  onUsernameChange(event: any) {
    const input = event.target.value;
    event.target.value = input.replace(/\s+/g, ''); // Remove whitespace
  }
  
  checkPassword() {
    const password = this.signupForm.get('password').value;
    this.passwordLengthValid = password.length >= 8;
    this.passwordUpperCaseValid = /[A-Z]/.test(password);
    this.passwordLowerCaseValid = /[a-z]/.test(password);
    this.passwordNumberValid = /[0-9]/.test(password);
    this.passwordSpecialCharValid = /[!@#$%^&*(),.?":{}|<>]/.test(password);
    this.passwordValid = this.passwordLengthValid && this.passwordUpperCaseValid && this.passwordLowerCaseValid && this.passwordNumberValid && this.passwordSpecialCharValid;
  }

  toggleTermsAndConditions() {
    this.termsAndConditionsAccepted = !this.termsAndConditionsAccepted;
  }
}
