import { Component, signal } from '@angular/core';
import {
  FormControl,
  FormGroup,
  FormsModule,
  ReactiveFormsModule,
  Validators,
} from '@angular/forms';
import { CommonModule } from '@angular/common';
import { MatCardModule } from '@angular/material/card';
import { MatListModule } from '@angular/material/list';
import { MatSelectModule } from '@angular/material/select';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { HttpClient } from '@angular/common/http';
import { forkJoin, map } from 'rxjs';
import { WidgetService } from 'src/app/widget-configuration.service';

@Component({
  selector: 'app-mail',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    MatCardModule,
    MatListModule,
    MatFormFieldModule,
    MatInputModule,
    MatSelectModule,
    MatButtonModule,
  ],
  templateUrl: './mail.component.html',
  styleUrl: './mail.component.scss',
})
export class MailComponent {
  client: any;
  widgetConf: any;
  serverUrl: string;
  formId!: string;

  dynamicForm: FormGroup = new FormGroup({});
  fields = signal<any[]>([]);

  mailServices = signal<any[]>([]);
  selectedService = new FormControl();
  bodyMessage = new FormControl();

  mailSent = signal<boolean>(false);
  mailError = signal<boolean>(false);

  constructor(
    private widgetService: WidgetService,
    private http: HttpClient
  ) {
    this.client = this.widgetService.getClient();
    this.serverUrl = this.widgetService.getServerUrl();
    this.widgetConf = this.client.getConfiguration();

    this.loadMailServices();
    this.loadFormConfigurations();
  }


  // recupero i servizi disponibili per il canale MAIL
  private loadMailServices() {
    const services = this.widgetConf.servicesConfiguration
      .filter((conf: any) => conf.type === 'MAIL')
      .flatMap((conf: any) => conf.services);

    console.log('Servizi MAIL:', services);
    this.mailServices.set(services);
  }


  // recupero il form associato ai vari servizi (in modo da sapere quali campi vanno compilati e inviati all'apertura di una nuova sessione)
  private loadFormConfigurations() {
    const formRequests: any[] = [];
    const seenFormIds = new Set<string>();

    this.widgetConf.servicesConfiguration?.forEach((conf: any) => {
      conf.services?.forEach((service: any) => {
        if (service.formId && !seenFormIds.has(service.formId)) {
          seenFormIds.add(service.formId);
          this.formId = service.formId;

          const request$ = this.http
            .get(`${this.serverUrl}/apps/widget/conf/forms/form_${service.formId}.json`)
            .pipe(
              map((config: any) => ({
                formId: service.formId,
                config,
              }))
            );

          formRequests.push(request$);
        }
      });
    });

    if (formRequests.length) {
      forkJoin(formRequests).subscribe((formConfigs: any[]) => {
        console.log('Form configs ricevuti:', formConfigs);

        const allFields = formConfigs.flatMap(fc => fc.config.fields || []);
        const sortedFields = allFields.sort((a, b) => +a.order - +b.order);

        this.fields.set(sortedFields);
        this.buildForm(sortedFields);
      });
    }
  }

  // costruisco il form con i campi che mi sono arrivati dal json del form configurato
  private buildForm(fields: any[]) {
    const formGroup: { [key: string]: FormControl } = {};

    fields.forEach((field) => {
      const validators = [];

      if (field.required === 'TRUE') {
        validators.push(Validators.required);
      }

      if (field.validationPattern) {
        validators.push(Validators.pattern(field.validationPattern));
      }

      formGroup[field.key] = new FormControl(field.defaultValue || '', validators);
    });

    this.dynamicForm = new FormGroup(formGroup);
    console.log('Form created:', this.dynamicForm);
  }

  // creazione nuova sessione MAIL
  newMailChannelSession() {
    if (this.dynamicForm.invalid) return;

    const formValues = this.dynamicForm.value;

    const formattedFields = this.fields().map((field: any) => ({
      id: field.key,
      label: field.label,
      value: formValues[field.key],
    }));

    // metodo per creare nuova sessione MAIL 
    this.client
      .mailChannelSessionNew({ 
        force: false,
        service: this.selectedService.value?.code,
        widgetId: this.widgetService.getWidgetId(),
        widgetFormId: this.formId,
        body: this.bodyMessage.value,
        fields: formattedFields,
      })
      .then((res: any) => {
        console.log('mailChannelSessionNew SUCCESS');
        console.log('Number of ticket created:', res);
        this.mailSent.set(true);
      })
      .catch((err: any) => {
        console.error('mailChannelSessionNew ERROR', err);
        this.mailSent.set(true);
        this.mailError.set(true);
      });
  }
}
