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;
  myForm: FormGroup;
  dataMasterStatus: any;

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

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

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

  editForm() {
    this.myForm = this.fb.group({
      id: this.dataRow.id,
      name: this.dataRow.name,
      status: this.dataRow.status,
      headerId: this.dataRow.headerId,
    });
  }

  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)`);
    }
  }
}
