import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Rn_Forms_Component_Setup } from 'src/app/models/fnd/Rn_Forms_Component_Setup';
import { Rn_Forms_Setup } from 'src/app/models/fnd/Rn_Forms_Setup';
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";
@Component({
  selector: 'app-editdynamicform',
  templateUrl: './editdynamicform.component.html',
  styleUrls: ['./editdynamicform.component.scss']
})
export class EditdynamicformComponent implements OnInit {
  updated = false;
  fieldErrors: ValidationError[] = [];
  rn_froms_setup: Rn_Forms_Setup;
  components: Rn_Forms_Component_Setup[];
  id: number;

  related_to = ["Menu", "Related To"];
  page_event = ["OnClick", "OnBlur"];
  field_type = [
    "textfield",
    "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 router: Router,
    private route: ActivatedRoute,
    private dynamicservice: DynamicformService,
    private httpService: HttpClient) { }

  ngOnInit(): void {
    // this.getMapings();
    this.rn_froms_setup = new Rn_Forms_Setup();
    this.id = this.route.snapshot.params["id"];
    console.log("update with id = ", this.id);
    this.getById(this.id);
  }
  getById(id: number) {
    this.dynamicservice.getById(id).subscribe((data) => {
      this.rn_froms_setup = data;
      this.components = data.components;
      console.log('component length = ', this.components.length.toString());

    });
  }
  update() {
    this.fieldErrors = [];
    this.dynamicservice.update(this.id, this.rn_froms_setup).subscribe(
      (data) => {
        console.log(data);
        this.router.navigate(["../../all"], { relativeTo: this.route });
      },
      (error: HttpErrorResponse) => {
        /* (error: HttpErrorResponse) => { */
        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
        this.rn_froms_setup = new Rn_Forms_Setup();

      }
    );
  }
  onSubmit() {
    this.updated = true;
    this.update();
  }

  getFilteredMappings(index: number) {
    if (!this.components) return this.mappings;

    const selectedValues = this.components
      .map((comp, i) => {
        if (i === index) return null;
        return comp.mapping;
      })
      .filter(val => val !== null && val !== 'null' && val !== '');

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

  // Tag Input Helpers for Edit Mode
  getDropValuesArray(index: number): string[] {
    const component = this.components[index];
    const val = component.drop_values;
    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 component = this.components[index];
    const currentArr = this.getDropValuesArray(index);

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

  removeDropValue(index: number, valueToRemove: string) {
    const component = this.components[index];
    let currentArr = this.getDropValuesArray(index);
    currentArr = currentArr.filter(v => v !== valueToRemove);
    component.drop_values = currentArr.join(',');
  }
  //   this.httpService
  //     .get<Mapping[]>("./assets/json/form-setup-mapping.json")
  //     .subscribe(
  //       (data) => {
  //         console.log(data);
  //         this.mappings = data;
  //       },
  //       (err) => console.log(err)
  //     );
  // }
  back() {
    this.router.navigate(["../../all"], { relativeTo: this.route });
  }
}
