import { HttpErrorResponse } from '@angular/common/http';
import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { lastValueFrom, map, startWith } from 'rxjs';
import * as reserved_words from 'src/assets/json/reserved_words.json';
import { DynamicFormService } from 'src/app/services/forms-management/dynamic-form.service';
import { TableManagementService } from 'src/app/services/forms-management/table-management.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import * as data from 'src/assets/json/icons.json';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-configure-select',
  templateUrl: './configure-select.component.html',
  styleUrls: ['./configure-select.component.css'],
})
export class ConfigureSelectComponent implements OnInit {
  public formGroup: FormGroup;
  public arrSelect: Array<string>;
  public arrGrupos: Array<string>;
  public arrOption: Array<any>;

  public num_cols: number;
  public arr_columns: Array<string>;

  public arr_relationship: Array<any> = [];
  public arr_column: Array<any> = [];

  public arr_tables_rel: Array<any> = [];
  public arr_columns_rel: Array<any> = [];

  public opc_select_disable: boolean = false;

  public arr_columns_main: any = [];
  public arr_tabla_mm: any = [];
  public isTablaMM: boolean = false;

  public arr_icons: Array<any> = [];

  public opcion:string = '';
  public valor:string = '';

  @ViewChild("nombreGrupo") nombreGrupo: any;
  filteredOptions?: Observable<string[]>;

  constructor(
    private _DynamicFormService: DynamicFormService,
    private _resourceService: ResourcesService,
    private _getbgtService: TableManagementService,
    public dialogRef: MatDialogRef<ConfigureSelectComponent>,
    public resourcesService: ResourcesService,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.getColumnMain(data.table_main);
    this.num_cols = data.num_cols;
    this.arr_columns = data.column;


    this.arr_tables_rel = data.tables_rel;
    this.arr_columns_rel = data.columns;

    this.arrSelect = [];
    this.arrGrupos = [];
    this.arrOption = [];
    this.formGroup = this.createFormGroup();
  }

  ngOnInit(): void {
    let data_icons = data;
    this.arr_icons = data_icons.icons;
    let arr_icons_aux: any = [];

    this.arr_icons.map((element) => {
      if (!arr_icons_aux.includes(element.name)) {
        arr_icons_aux.push(element.name);
      }
    });
    this.arr_icons = arr_icons_aux;

    this.filteredOptions = this.formGroup.controls['icon']?.valueChanges.pipe(
      startWith(''),
      map(value => this._filter(value || '')),
    );
  }

  private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();
    return this.arr_icons.filter(option => option.toLowerCase().includes(filterValue));
  }

  private createFormGroup() {
    return new FormGroup({
      tag: new FormControl('select', Validators.required),
      column: new FormControl('', Validators.required),

      table_rel: new FormControl({
        value: '',
        disabled: this.arr_tables_rel.length === 0,
      }),
      column_rel: new FormControl({
        value: '',
        disabled: this.arr_tables_rel.length === 0,
      }),

      label: new FormControl('', Validators.required),
      id: new FormControl('', [Validators.required, this.applyFilterControl]),
      name: new FormControl('', Validators.required),
      value: new FormControl({ value: '', disabled: true }),
      icon: new FormControl(''),
      required_reg: new FormControl(false),
      required_mod: new FormControl(false),
      disabled_reg: new FormControl(false),
      disabled_mod: new FormControl(false),
      multi_select: new FormControl(false),
      group_select: new FormControl(false),
      data_select: new FormControl([]),
      deleted: new FormControl(true),
      num_col: new FormControl(1, Validators.required),
      num_row: new FormControl(1, Validators.required),
      columnMM: new FormControl(),
      columnMMtoMain: new FormControl(),
    });
  }

  // Obtener columnas
  public async dataColumns() {
    await lastValueFrom(
      this._getbgtService.getColumns({ tables: [this.formGroup.controls['table_rel']?.value.NOMBRE_TABLA] })
    ).then(
      (data: any) => {
        if (!data.error || data.response.length > 0) {
          this.arr_columns_rel = data.response[0].columns;
          this.opc_select_disable = true;
        } else this.opc_select_disable = false;
      },
      (error) => this._resourceService.checkErrors(error)
    );
  }

  public async getDataSelect() {
    let resp = { table: this.formGroup.controls['table_rel']?.value.NOMBRE_TABLA, column: this.formGroup.controls['column_rel']?.value };
    await lastValueFrom(this._DynamicFormService.getDataSelect(resp)).then(
      (data: any) => {
        if (!data.error) this.formGroup.controls['data_select']?.setValue(data.response);
      },
      (error: HttpErrorResponse) => this._resourceService.checkErrors(error)
    );
  }

  public selectionMultipleSelect() {
    if (!this.formGroup.controls['multi_select']!.value) this.formGroup.controls['group_select']?.setValue(false);
    this.arrGrupos = [];
    this.formGroup.controls['data_select']?.setValue([]);
    this.arrOption = [];
  }

  public removeData() {
    this.arrGrupos = [];
    // this.data_select?.setValue([]);
    this.arrOption = [];
    if (!this.formGroup.controls['group_select']!.value) this.formGroup.controls['multi_select']?.setValue(false);
  }

  public addGroup(nombreGrupo: string) {
    if (!this.arrGrupos.includes(nombreGrupo) && nombreGrupo !== '') {
      this.arrGrupos.push(nombreGrupo);
      this.resourcesService.openSnackBar('Grupo añadido');
      this.nombreGrupo.nativeElement.value = "";
    }
  }

  public addOption(grupo: string) {

    if (this.formGroup.controls['group_select']!.value && grupo == undefined){
      this.resourcesService.openSnackBar('Debe seleccionar un grupo');
    } else if (this.opcion == '' || this.valor == ''){
      this.resourcesService.openSnackBar('Los campos opción y valor son obligatorios');
    } else if (this.formGroup.controls['group_select']!.value) {
      if (grupo !== undefined) {
        let auxArr: any[] = [];
        this.formGroup.controls['data_select']!.value.forEach(
          (element: any) => (auxArr = element.datos)
        );
        let filter = auxArr.filter((element) => element.valor == this.valor);
        if (filter.length == 0) {
          let index = this.formGroup.controls['data_select']!.value.findIndex(
            (element: any) => element.grupo == grupo
          );
          if (index !== -1)
            this.formGroup.controls['data_select']!.value[index].datos.push({
              opcion: this.opcion,
              valor: this.valor,
            });
          else {
            this.formGroup.controls['data_select']!.value.push({
              grupo: grupo,
              datos: [{ opcion: this.opcion, valor: this.valor }],
            });
            this.resourcesService.openSnackBar('Opción añadida');
          }
        } else this.resourcesService.openSnackBar('Los valores no pueden repetirse');
      } else this.resourcesService.openSnackBar('Debe seleccionar un grupo');
    } else {
      let filter = this.formGroup.controls['data_select']!.value.filter(
        (element: any) => element.valor == this.valor
      );
      if (filter.length == 0) {
        this.formGroup.controls['data_select']!.value.push({
          opcion: this.opcion,
          valor: this.valor,
          grupo: grupo,
        });
        this.resourcesService.openSnackBar('Opción añadida');
      } else this.resourcesService.openSnackBar('Los valores no pueden repetirse');
    }
    this.opcion = '';
    this.valor = '';
  }

  public numColumn(type: string) {
    if (type == 'add' && this.formGroup.controls['num_col']?.value + 1 <= this.num_cols)
      this.formGroup.controls['num_col']?.setValue(this.formGroup.controls['num_col']?.value + 1);
    else if (this.formGroup.controls['num_col']?.value - 1 >= 1)
      this.formGroup.controls['num_col']?.setValue(this.formGroup.controls['num_col']?.value - 1);
  }

  private applyFilterControl(control: any) {
    const filterValue = control.value;
    let arrWords = reserved_words;
    let filter = arrWords.reserved_words.filter(
      (element: string) => element == filterValue.trim().toUpperCase()
    );
    if (filter.length > 0) {
      this.resourcesService.openSnackBar(`${filterValue} es una palabra reservada`);
      return { validWords: { word: filterValue } };
    }
    return null;
  }

  public onChangeColumn() {
    let valueColumn = this.formGroup.controls['column']?.value;
    let arrTableMM = this.arr_columns_rel.filter((element: any) => element.type == 'De M:M');

    arrTableMM.map((infoTabla: any) => {
      infoTabla.columns.map((column: string) => {
        if (valueColumn === column) {
          this.arr_tabla_mm = infoTabla;
          let arrTemp: any = [];
          this.arr_tabla_mm['columns'].map((columns: any) => {
            arrTemp.push({ column: columns, table: this.arr_tabla_mm['table'] });
          });
          this.arr_tabla_mm = arrTemp;
          this.isTablaMM = true;
        }
      });
    });

    this.formGroup.controls['name']?.setValue(valueColumn);
    this.formGroup.controls['id']?.setValue(valueColumn);
  }

  private async getColumnMain(table_name: string) {
    await lastValueFrom(this._getbgtService.getColumns({ tables: [table_name] })).then(
      (data: any) => {
        if (!data.error) {
          this.arr_columns_main = data.response[0];
          let arrTemp: any = [];
          this.arr_columns_main['columns'].map((columns: any) => {
            arrTemp.push({ column: columns, table: this.arr_columns_main['table'] });
          });
          this.arr_columns_main = arrTemp;
        }
      },
      (error: HttpErrorResponse) => this._resourceService.checkErrors(error)
    );
  }
}
