import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ValidationError } from 'src/app/models/fnd/ValidationError';
import { DynamicformService } from 'src/app/services/fnd/dynamicform.service';
import { Mapping } from "src/app/models/fnd/Mapping";
import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-adddynamicform',
  templateUrl: './adddynamicform.component.html',
  styleUrls: ['./adddynamicform.component.scss']
})
export class AdddynamicformComponent implements OnInit {
  public entryForm: FormGroup;
  submitted = false;
  basic: boolean = false;
  fieldErrors: ValidationError[] = [];
  related_to = ['Menu', 'Related To'];
  page_event = ['OnClick', 'OnBlur'];
  field_type = ['text', 'dropdown', 'date', 'checkbox', 'textarea', 'togglebutton'];
  // mappings: Mapping[];
  mappings = [
    { label: 'textfield1', value: 'comp1' },
    { label: 'textfield2', value: 'comp2' },
    { label: 'textfield3', value: 'comp3' },
    { label: 'textfield4', value: 'comp4' },
    { label: 'textfield5', value: 'comp5' },
    { label: 'textfield6', value: 'comp6' },
    { label: 'textfield7', value: 'comp7' },
    { label: 'textfield8', value: 'comp8' },
    { label: 'textfield9', value: 'comp9' },
    { label: 'textfield10', value: 'comp10' },
    { label: 'textfield11', value: 'comp11' },
    { label: 'textfield12', value: 'comp12' },
    { label: 'textfield13', value: 'comp13' },
    { label: 'textfield14', value: 'comp14' },
    { label: 'textfield15', value: 'comp15' },
    { label: 'textfield16', value: 'comp16' },
    { label: 'textfield17', value: 'comp17' },
    { label: 'textfield18', value: 'comp18' },
    { label: 'textfield19', value: 'comp19' },
    { label: 'textfield20', value: 'comp20' },
    { label: 'textfield21', value: 'comp21' },
    { label: 'textfield22', value: 'comp22' },
    { label: 'textfield23', value: 'comp23' },
    { label: 'textfield24', value: 'comp24' },
    { label: 'textfield25', value: 'comp25' },
    { label: 'textfield26', value: 'comp26' },
    { label: 'longtext1', value: 'comp_l27' },
    { label: 'longtext2', value: 'comp_l28' },
    { label: 'longtext3', value: 'comp_l29' },
    { label: 'longtext4', value: 'comp_l30' }
  ];



  constructor(private _fb: FormBuilder,
    private router: Router,
    private toastr: ToastrService,
    private dynamicservice: DynamicformService,
    private httpService: HttpClient,
    private route: ActivatedRoute,) { }

  ngOnInit(): void {
    // this.getMapings();
    console.log(this.mappings);
    this.entryForm = this._fb.group({
      form_name: [null],
      form_desc: [null],
      related_to: [null],
      page_event: [null],
      button_caption: [null],
      components: this._fb.array([this.initLinesForm()]),
    });
  }
  // getMapings() {
  //   this.httpService
  //     .get<Mapping[]>('./assets/json/form-setup-mapping.json')
  //     .subscribe(data => {
  //       console.log(data);
  //       this.mappings = data;
  //       }, err => console.log(err)
  //     )
  // }
  initLinesForm() {
    return this._fb.group({
      label: [null],
      type: [null],
      mapping: [null],
      mandatory: [null],
      readonly: [null],
      drop_values: [null],
      sp: [null],
    });
  }

  get controls() {
    return (this.entryForm.get("components") as FormArray).controls;
  }

  getFilteredMappings(index: number) {
    const components = this.entryForm.get('components') as FormArray;
    // Get all selected values from other rows
    const selectedValues = components.controls
      .map((control, i) => {
        if (i === index) return null; // Don't block current row's value
        return control.get('mapping').value;
      })
      .filter(val => val !== null && val !== 'null' && val !== '');

    // Return mappings that remain
    return this.mappings.filter(m => !selectedValues.includes(m.value));
  }

  // Tag Input Helpers
  getDropValuesArray(index: number): string[] {
    const control = (this.entryForm.get('components') as FormArray).at(index).get('drop_values');
    const val = control.value;
    if (!val) return [];
    return val.split(',').map(s => s.trim()).filter(s => s.length > 0);
  }

  addDropValue(index: number, event: any) {
    const value = event.target.value;
    if (!value) return;

    const control = (this.entryForm.get('components') as FormArray).at(index).get('drop_values');
    const currentArr = this.getDropValuesArray(index);

    if (!currentArr.includes(value.trim())) {
      currentArr.push(value.trim());
      control.setValue(currentArr.join(','));
    }
    event.target.value = ''; // Clear input
  }

  removeDropValue(index: number, valueToRemove: string) {
    const control = (this.entryForm.get('components') as FormArray).at(index).get('drop_values');
    let currentArr = this.getDropValuesArray(index);
    currentArr = currentArr.filter(v => v !== valueToRemove);
    control.setValue(currentArr.join(','));
  }

  onAddLines() {
    (<FormArray>this.entryForm.get("components")).push(this.initLinesForm());
  }

  onRemoveLines(index: number) {
    (<FormArray>this.entryForm.get("components")).removeAt(index);
  }
  onSubmit() {
    console.log(this.entryForm.value);
    this.dynamicservice.create(this.entryForm.value).subscribe(
      (data) => {
        console.log(data);
        this.router.navigate(["../all"], { relativeTo: this.route });
        if (data) {
          this.toastr.success('Added successfully');
        }
      },
      (error) => {
        console.log(error);
        const objectArray = Object.entries(error.error.fieldErrors);
        objectArray.forEach(([k, v]) => {
          console.log(k);
          console.log(v);
          this.fieldErrors.push({ field: k, message: v });
        });
        console.log(this.fieldErrors); // this will come from backend
        if (error) {
          this.toastr.error('Not Added Data Getting Some Error');
        }
      }
    );
  }
}
