import { Component, inject, signal } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { cssCheck, cssPin, cssAlarm, cssLock } from '@ng-icons/css.gg';
import { OpenPanelService } from '@core/services/openpanel.service';
import { n8nEnvironment } from '../../../../../environments/n8n';

@Component({
  selector: 'app-contact',
  imports: [ReactiveFormsModule, NgIcon],
  viewProviders: [provideIcons({ cssCheck, cssPin, cssAlarm, cssLock })],
  templateUrl: './contact.component.html',
  styleUrl: './contact.component.scss',
})
export class ContactComponent {
  private readonly fb = inject(FormBuilder);
  private readonly op = inject(OpenPanelService);
  private readonly http = inject(HttpClient);

  readonly submitted = signal(false);
  readonly sending = signal(false);
  readonly sendError = signal(false);
  private hasStarted = false;

  readonly form = this.fb.nonNullable.group({
    name: ['', [Validators.required, Validators.minLength(2)]],
    email: ['', [Validators.required, Validators.email]],
    message: ['', [Validators.required, Validators.minLength(20)]],
  });

  onFirstFocus(): void {
    if (!this.hasStarted) {
      this.hasStarted = true;
      this.op.track('contact_form_start');
    }
  }

  onSubmit(): void {
    console.log('submit');
    if (this.form.invalid) {
      this.form.markAllAsTouched();
      this.op.track('contact_form_validation_error');
      return;
    }

    this.op.track('contact_form_submit', {
      message_length: this.form.value.message?.length ?? 0,
    });

    this.sending.set(true);
    this.sendError.set(false);

    console.log('posting to', n8nEnvironment.contactWebhookUrl, 'with payload', this.form.getRawValue());

    this.http
      .post(n8nEnvironment.contactWebhookUrl, this.form.getRawValue())
      .subscribe({
        next: () => {
          this.submitted.set(true);
          this.form.reset();
          this.hasStarted = false;
          this.sending.set(false);
        },
        error: () => {
          this.sendError.set(true);
          this.sending.set(false);
          this.op.track('contact_form_send_error');
        },
      });
  }

  resetForm(): void {
    this.submitted.set(false);
  }

  get nameInvalid(): boolean {
    const c = this.form.controls.name;
    return c.invalid && c.touched;
  }

  get emailInvalid(): boolean {
    const c = this.form.controls.email;
    return c.invalid && c.touched;
  }

  get messageInvalid(): boolean {
    const c = this.form.controls.message;
    return c.invalid && c.touched;
  }
}
