import { Component, OnInit } from '@angular/core';
import { FormsService } from '../_services/forms.service';
import {FormGroup, ReactiveFormsModule, FormBuilder, Validators} from "@angular/forms";
import {ActivatedRoute, Router} from "@angular/router";
import {NgIf} from "@angular/common";
import {Metrika} from "ng-yandex-metrika";
declare var gtag

@Component({
  selector: 'request',
  standalone: true,
  imports: [ReactiveFormsModule, NgIf],
  templateUrl: './request.component.html',
  styleUrl: './request.component.scss'
})
export class RequestComponent implements OnInit {
  public hidden = true;
  public success = false;
  public feedbackForm: FormGroup;

  public utmSource:string;
  public utmMedium:string;
  public utmCampaign:string;
  public utmContent:string;
  public utmTerm:string;

  constructor(private formBuilder:FormBuilder, private formsService: FormsService, private router: ActivatedRoute, private metrika: Metrika) {
    this.router.queryParams.subscribe(params =>{
      this.utmSource = params['utm_source'];
      this.utmMedium = params['utm_medium'];
      this.utmCampaign = params['utm_campaign'];
      this.utmContent = params['utm_content'];
      this.utmTerm = params['utm_term']
    })
  }

  ngOnInit():void{
    this.feedbackForm = this.formBuilder.group({
      'feedback-name':['',Validators.required],
      'feedback-email':['',[
        Validators.required,
        Validators.pattern( /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|.(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ )
      ]],
      'feedback-number':['', Validators.pattern(/^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/)],
      'feedback-add-number':['', Validators.pattern(/^[0-9]{1,6}$/)],
      'feedback-message':['',Validators.required],
      mailto:['info@nirgroup.ru'],
      type:['feedback-form-support'],
      'utm-source':[this.utmSource],
      'utm-medium':[this.utmMedium],
      'utm-campaign':[this.utmCampaign],
      'utm-content':[this.utmContent],
      'utm-term':[this.utmTerm]
    });
  }

  open(){
    this.hidden = false;
    this.success = false;
    this.metrika.reachGoal('form-open').then();
    gtag('event', 'form-open', {'event_name':'form-open',
      'value': 'form-open'   })
    this.ngOnInit()
  }

  close(){
    this.feedbackForm.reset();
    this.hidden = true;
    this.success = false;
  }

  onSubmit(){
    this.feedbackForm.markAllAsTouched();
    if (this.feedbackForm.valid)
      this.formsService.save('model', 'feedback-form-support', null, this.feedbackForm.value).subscribe(res => {
        this.metrika.reachGoal('form-sent').then();
        gtag('event', 'form-sent', {'event_name':'form-sent',
          'value': 'form-sent'   })
        this.success = true;
      }, error => {
        console.log(error);
      });
  }
}
