import { Component, Input, OnInit } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { NgbActiveModal } from "@ng-bootstrap/ng-bootstrap";
import { BuildingService } from "../../service/monitoring-api.service";

@Component({
  selector: "app-add-edit-master",
  templateUrl: "./add-edit-master.component.html",
  styleUrls: ["./add-edit-master.component.css"],
})
export class AddEditMasterComponent implements OnInit {
  @Input() headerId: number;
  @Input() dataRow: any;
  @Input() mode: any;
  @Input() category: boolean = false;
  myForm: FormGroup;
  dataMasterStatus: any;
  selectedIcon: string = '';

  constructor(
    public activeModal: NgbActiveModal,
    private fb: FormBuilder,
    private monitoringApiService: BuildingService
  ) {}

  ngOnInit() {
    this.createForm();
    this.dataListMaster();
    console.log(this.dataRow);
    
    if (this.dataRow) {
      this.editForm();
    }
  }

  createForm() {
    const formControls = {
      name: ["", Validators.required],
      status: [2, Validators.required],
      headerId: this.headerId
    };

    if (this.category) {
      formControls['icon'] = [undefined, Validators.required];
    }

    this.myForm = this.fb.group(formControls);
  }

  editForm() {
    const formControls = {
      id: this.dataRow.id,
      name: this.dataRow.name,
      status: this.dataRow.status,
      headerId: this.dataRow.headerId,
    };

    if (this.category) {
      formControls['icon'] = this.dataRow.icon || "";
      this.selectedIcon = this.dataRow.icon || "";
    }

    this.myForm = this.fb.group(formControls);
  }

  dataListMaster() {
    this.monitoringApiService.getMasterListData().subscribe((data) => {
      const dataCategory = data.data.find(
        (item) => item.name === "master_status"
      ).headerDetailParam;
      this.dataMasterStatus = dataCategory.filter(item => item.status === "2");
    });
  }

  addRow() {
    if (this.myForm.valid) {
      this.activeModal.close(this.myForm.value);
    }
  }

  addDepartment() {
    let newDept = prompt("Enter new department name:");
    if (newDept) {
      alert(`Department ${newDept} added! (simulated)`);
    }
  }

  onIconSelected(icon: string): void {
    console.log(icon);
    
    this.selectedIcon = icon;
    this.myForm.get('icon').setValue(icon);  // Set nilai icon ke dalam form
  }
}
