import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { TableApiService } from 'src/app/_services/table-api.service';
import { BuildingService } from '../../service/monitoring-api.service';
import { AddEditMasterComponent } from '../add-edit-master/add-edit-master.component';

@Component({
  selector: 'app-master-status',
  templateUrl: './master-status.component.html',
  styleUrls: ['./master-status.component.css']
})
export class MasterStatusComponent {
  data: any;
  filteredRows: any[];
  searchTerm: string = "";
  rows: any = [];
  public breadcrumb: any;
  dataMasterCategori: any;

  constructor(
    private tableApiservice: TableApiService,
    private modalService: NgbModal,
    private router: Router,
    private monitoringApiService: BuildingService
  ) {}

  ngOnInit() {
    this.breadcrumb = {
      mainlabel: "Master Status",
      links: [
        {
          name: "Home",
          isLink: false,
        },
        {
          name: "Master Status",
          isLink: false,
        },
      ],
    };
    this.fetchData();
  }

  fetchData() {
    this.monitoringApiService.getMasterData().subscribe((res) => {
      this.data = res.results.data;
      this.dataMasterCategori = res.results.data.find(
        (item) => item.name === "master_status"
      );
      this.filteredRows = this.dataMasterCategori.headerDetailParam;
    });
  }

  filterRows() {
    if (!this.searchTerm) {
      this.filteredRows = [
        ...this.data.find((item) => item.name === "master_status")
          .headerDetailParam,
      ];
    } else {
      this.filteredRows = this.data
        .find((item) => item.name === "master_status")
        .headerDetailParam.filter((row) => this.rowContainsSearchTerm(row));
    }
  }

  rowContainsSearchTerm(row: any): boolean {
    const searchTermLC = this.searchTerm.toLowerCase();
    return Object.values(row).some(
      (value) =>
        value !== null && value.toString().toLowerCase().includes(searchTermLC)
    );
  }

  openAddMasterModal() {
    const modalRef = this.modalService.open(AddEditMasterComponent, {
      size: "lg",
    });

    modalRef.componentInstance.headerId = this.dataMasterCategori.id;
    modalRef.componentInstance.mode = "add";
    modalRef.result.then(
      (result) => {
        console.log(result);
        if (result) {
          this.monitoringApiService
            .postHeaderDetailParam(result)
            .subscribe((res) => {
              console.log(res);
              this.fetchData();
            });
        }
      },
      (reason) => {
        console.log(`Dismissed: ${reason}`);
      }
    );
  }

  editRow(row) {
    const modalRef = this.modalService.open(AddEditMasterComponent, {
      size: "lg",
    });

    modalRef.componentInstance.headerId = this.dataMasterCategori.id;
    modalRef.componentInstance.dataRow = row;
    modalRef.componentInstance.mode = "edit";
    modalRef.result.then(
      (result) => {
        console.log(result);
        if (result) {
          this.monitoringApiService
            .putHeaderDetailParam(result, row.id)
            .subscribe((res) => {
              console.log(res);
              this.fetchData();
            });
        }
      },
      (reason) => {
        console.log(`Dismissed: ${reason}`);
      }
    );
  }

  deleteRow(row) {
    const confirmDelete = confirm("Are you sure you want to delete this item?");
    if (confirmDelete) {
      this.monitoringApiService
        .deleteHeaderDetailParam(row.id)
        .subscribe((res) => {
          this.fetchData();
        });
    }
  }
}
