import { Component, Input } 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-building",
  templateUrl: "./add-edit-master-building.component.html",
  styleUrls: ["./add-edit-master-building.component.css"],
})
export class AddEditMasterBuildingComponent {
  @Input() dataRow: any;
  @Input() mode: any;
  myForm: FormGroup;

  data: any;
  dataStatus: any[];
  filteredDataStatus: any[];
  dataMasterStatus: any;

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

  ngOnInit() {
    this.createForm();
    this.listDataStatus();

    if (this.dataRow) {
      this.editForm();
    }
  }

  createForm() {
    this.myForm = this.fb.group({
      name: ["", Validators.required],
      statusId: [0, Validators.required],
      email: ["", Validators.required],
      owner: ["", Validators.required],
      address: ["", Validators.required],
      phone: ["", Validators.required],
      kwh: ["", Validators.required],
    });
  }

  editForm() {
    this.myForm = this.fb.group({
      id: this.dataRow.id,
      name: this.dataRow.name,
      statusId: this.dataRow.statusId,
      email: this.dataRow.email,
      owner: this.dataRow.owner,
      address: this.dataRow.address,
      phone: this.dataRow.phone,
      kwh: this.dataRow.kwh,
    });
  }

  listDataStatus() {
    this.monitoringApiService.getMasterData().subscribe((res) => {
      this.data = res.results.data;
      this.dataMasterStatus = res.results.data.find(
        (item) => item.name === "master_status"
      );
      this.dataStatus = this.dataMasterStatus.headerDetailParam;
      console.log(this.dataStatus);
      
      this.filteredDataStatus = this.dataStatus.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)`);
    }
  }
}
