import { Component, OnInit, inject, ViewChildren, QueryList, ElementRef, Input } from '@angular/core';
import { EndPoint } from '../../services/endpoint.service';
import { AnswerStandard } from '../../services/answerstandard.service';
import { FormBuilder, FormControl, FormGroup, ReactiveFormsModule, UntypedFormBuilder, Validators, } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { NgxMaskDirective, NgxMaskPipe } from 'ngx-mask';
import { Router, RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
import { Address } from '../../models/zipadress';
import { GenericValidator } from '../../models/cpfCnpjValidator';
import { AnonymousSubject } from 'rxjs/internal/Subject';



@Component({
    selector: 'app-signin',
    imports: [ReactiveFormsModule, CommonModule, NgxMaskDirective, NgxMaskPipe, RouterLink, RouterLinkActive, RouterOutlet],
    templateUrl: './signin.component.html',
    styleUrls: ['./signin.component.scss'],
    providers: []
})
export class SigninComponent implements OnInit {
  @ViewChildren('inputCpf, inputName, inputEmail, inputTel, inputZipCode, inputStreet, inputNumero, inputComplemento, inputBairro, inputCity, inputUf, inputTerms')
  formElements!: QueryList<ElementRef>;
  private endpoint = inject(EndPoint)


  

  backgroundImg: string = '';
  logo: string = 'https://aamepettatix.vtexassets.com/assets/vtex.file-manager-graphql/images/cd3eee51-7f40-4057-863c-c50f0c307b09___4959c02edbc2e66fbfdd532294516df3.png';
  mainStyle: { [key: string]: string } = {};
  errorMessage: string = '';
  cepErrorMessage: string= '';
  isSubmitting: boolean = false;
  isCepLoaded: boolean = false;
  userNotExists: boolean = false;
  send: boolean = false;
  zipCode: any[] = [];
  signForm: FormGroup;
 


  constructor(
    private formBuilder: UntypedFormBuilder,
    private router: Router) {
    this.signForm = this.formBuilder.group({
      cpf: this.formBuilder.control('', [Validators.required, GenericValidator.isValidCpf()]),
      name: this.formBuilder.control('', [Validators.required, Validators.pattern(/^[a-zA-Z]{2,}(?: [a-zA-Z]{2,})+$/)]),
      email: this.formBuilder.control('', [Validators.required, Validators.pattern(/^[a-z0-9._]+@[a-z0-9]+\.[a-z]+\.?([a-z]+)?$/i)]),
      tel: this.formBuilder.control('', [Validators.required, Validators.pattern(/^[0-9]{2,}([0-9]{8,9})+$/)]),
      cep: this.formBuilder.control('', [Validators.required,]),
      logradouro: this.formBuilder.control('', [Validators.required]),
      numero: this.formBuilder.control('', [Validators.required]),
      complemento: this.formBuilder.control(''),
      bairro: this.formBuilder.control('',[Validators.required,]),
      localidade: this.formBuilder.control('', [Validators.required]),
      uf: this.formBuilder.control('', [Validators.required]),
      useterms: this.formBuilder.control(false, [Validators.requiredTrue])
    });
  }


  ngOnInit(): void {
    this.endpoint.config('').subscribe((resp: AnswerStandard) => {
      if (resp.result) {
        // this.backgroundImg = resp.result.background_img;
        this.logo = resp.result.logo;
        this.mainStyle = {
          'background-image': `url(${this.backgroundImg})`
        };
      }
    });

    // if (this.signForm.controls['cep'].value.minLength = 8){
    //   this.signForm.controls['cep'].valueChanges.subscribe(value => {
    //     this.actConsultCep();
    //   });
    // }
  

  }

  actExists() {
    this.isSubmitting = true;
    // let onlyNumber = libUtils.onlyNumber(this.signForm.controls['cpf'].value);
    if (this.signForm.controls['cpf'].valid) {

      this.endpoint
      .consultCustomer(this.signForm.value)
      .subscribe((resp: AnswerStandard) => {
        if (resp) {
          console.log(resp)
          this.login();
        } else {
            this.userNotExists = true;
            this.signForm.controls['cpf'].disable();
            this.isSubmitting = false;
          }
      },
      (err) => {

      }
      );
    }
  }

  

  submitForm() {
    if (this.signForm.controls['cpf'].valid) {
      this.actExists();
    } else {
      this.signForm.controls['cpf'].markAsTouched();
    }
  }
      // Object.values(this.signForm.controls).forEach(control => {
      //   control.markAsTouched();
      // });

  goBack() {
    this.userNotExists = false;
    this.signForm.controls['cpf'].enable();
    // this.showFinalizeSection = false;
  }

  actConsultCep() {
    this.isSubmitting = true
    // if (this.signForm.controls['cep'].valid) {
      this.endpoint
        .consultCep(this.signForm.controls['cep'].value)
        .subscribe((resp: AnswerStandard) => {
          if (resp.result) {

            console.log(resp)
            resp.result.forEach((item: any) => {
              this.isSubmitting= false;
              const address: Address = {
                cep: item.cep,
                bairro: item.bairro,
                localidade: item.localidade,
                logradouro: item.logradouro,
                uf: item.uf
              };
              this.zipCode.push(address);
              console.log(this.zipCode);

            });

            this.signForm.patchValue({
              cep: this.zipCode[0].cep,
              bairro: this.zipCode[0].bairro,
              localidade: this.zipCode[0].localidade,
              logradouro: this.zipCode[0].logradouro,
              uf: this.zipCode[0].uf
            });

            this.signForm.controls['bairro'].disable();
            this.signForm.controls['localidade'].disable();
            this.signForm.controls['logradouro'].disable();
            this.signForm.controls['uf'].disable();

            this.zipCode.splice(0);
            this.isCepLoaded = true;
            setTimeout(() => {
              this.focusOnNextEmptyField();
            },500);
            
          } else {
            this.cepErrorMessage = resp.message || 'Verifique o CEP, pois a consulta foi realizada, mas sem resultado.';
            this.isSubmitting = false;
          }
        },
          (error) => {
            console.error('Error Ocurred:', error);
            this.cepErrorMessage = 'Verifique o CEP, pois a consulta foi realizada, mas sem resultado.';
            this.isSubmitting = false;

          }
        );
    // }
  }

  focusOnNextEmptyField() {
    const formControls = this.formElements.toArray();
    console.log(this.formElements)
    for (let control of formControls) {
      if (!control.nativeElement.value) {
        control.nativeElement.focus();
        break;
      }
    }
    return true;
  }
  onSubmit(event: Event) {
    if (this.focusOnNextEmptyField()) {
      event.preventDefault();
    }
  }


  onSavecustomer() {
    this.send = true;
    this.signForm.controls['cpf'].enable();
    this.signForm.controls['bairro'].enable();
    this.signForm.controls['localidade'].enable();
    this.signForm.controls['logradouro'].enable();
    this.signForm.controls['uf'].enable();
    debugger;

    if(true) {

      const formData = {
        cpf: this.signForm.value.cpf,
        nome: this.signForm.value.name,
        emailcontato: this.signForm.value.email,
        telefonecontato: this.signForm.value.tel,
        enderecocep: this.signForm.value.cep,
        enderecobairro: this.signForm.value.bairro,
        cidade: this.signForm.value.localidade,
        endereco: this.signForm.value.logradouro,
        uf: this.signForm.value.uf,
        endereconumero: this.signForm.value.numero,
        enderecocomplemento: this.signForm.value.complemento,
        termosuso: this.signForm.value.useterms

      };

      debugger;
      const obj = this.signForm.value;
      this.endpoint
      .registerCustomer(formData)
      .subscribe((resp: AnswerStandard) => {
        if (resp.result) {
          console.log('Response from backend:', resp);
          this.login();
        } else {
          Object.values(this.signForm.controls).forEach(control => {
          control.markAsTouched();
      });
    }
      },
        (error) => {
          console.error('Error occurred:', error);
        }
      );
    }
  }

  login() {
    // Após autenticação bem-sucedida
    localStorage.setItem('token', 'seu-token-aqui'); // Substitua pelo token real
    
    // Redirecionar para a página inicial ou página solicitada
    const returnUrl = this.router.routerState.snapshot.url || '/home';
    this.router.navigate([returnUrl]);
  }
}

