import { Component, OnInit, ViewChild } from "@angular/core";
import { NgbModal } from "@ng-bootstrap/ng-bootstrap";
import { NgBlockUI, BlockUI } from "ng-block-ui";
import { TableApiService } from "src/app/_services/table-api.service";
import { ModalAddEditComponent } from "./modal-add-edit/modal-add-edit.component";
import { ActivatedRoute, Router } from "@angular/router";
import { BuildingService } from "../service/monitoring-api.service";

@Component({
  selector: "app-device",
  templateUrl: "./device.component.html",
  styleUrls: ["./device.component.css"],
})
export class DeviceComponent implements OnInit {
  data: any;
  totalOn: any;
  totalOff: any;
  filteredRows: any[];
  searchTerm: string = "";
  rows: any = [];
  public breadcrumb: any;
  spinnerActive: boolean = false;

  singlebasicSelected: any;

  singleSelectArray = [
    { item_id: 1, item_text: "Alaska" },
    { item_id: 2, item_text: "California" },
    { item_id: 3, item_text: "Colorado" },
    { item_id: 4, item_text: "New Mexico" },
    { item_id: 5, item_text: "Alabama" },
    { item_id: 6, item_text: "Connecticut" },
    { item_id: 7, item_text: "New York" },
  ];

  @BlockUI("zeroConfiguration") blockUIZeroConfiguration: NgBlockUI;

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

  ngOnInit() {
    this.breadcrumb = {
      mainlabel: "Device",
      links: [
        {
          name: "Home",
          isLink: false,
          link: "/dashboard/sales",
        },
        {
          name: "Device",
          isLink: false,
        },
      ],
    };
    this.fetchData();
  }

  fetchData() {
    this.monitoringApiService.getDeviceData().subscribe((res) => {
      this.data = res;
      this.filteredRows = this.data.results.data;
      console.log(this.filteredRows);
      this.totalOn = this.filteredRows.filter((row) => row.statusEntity.name.toLowerCase() === 'aktif').length
      this.totalOff = this.filteredRows.filter((row) => row.statusEntity.name.toLowerCase() === 'nonaktif').length
    });
  }

  filterRows() {
    if (!this.searchTerm) {
      this.filteredRows = [...this.data.results.data];
    } else {
      this.filteredRows = this.data.results.data.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)
    );
  }

  addFieldValue() {
    const modalRef = this.modalService.open(ModalAddEditComponent, {
      size: "lg",
    });
    modalRef.componentInstance.newAttribute = {
      id: null,
      name: "",
      position: "",
      office: "",
      age: "",
      salary: "",
      startdate: "",
    };

    modalRef.result.then(
      (result) => {
        if (result) {
          this.rows.push(result);
          this.rows = [...this.rows];
        }
      },
      (reason) => {
        console.log(`Dismissed: ${reason}`);
      }
    );
  }

  viewRow(row) {
    this.router.navigate(["/device/view", row.id]);
  }

  editRow(row) {
    this.router.navigate(["/device/edit", row.id]);
  }

  deleteRow(row) {
    console.log("Delete row:", row);
  }

  addDevice(): void {
    // Aktifkan spinner
    this.spinnerActive = true;
    this.monitoringApiService.getSyncDeviceData().subscribe((res) => {
      console.log(res);
    });
   
    setTimeout(() => {
      this.spinnerActive = false;
      this.fetchData();
    }, 3000);
  }
}
