import { Component, OnInit, ViewChild } from "@angular/core";
import { NgbModal } from "@ng-bootstrap/ng-bootstrap";
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";
import { DeviceService } from "../service/device.service";
import { ToastrService } from "ngx-toastr";
import * as FileSaver from "file-saver";
import * as XLSX from "xlsx";
import { TableexcelService } from "src/app/_services/tableexcel.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[];
  summaryTotal: any[];
  searchTerm: string = "";
  buildingSelected: any;
  statusSelected: any;
  categorySelected: any;
  dataMasterCategori: any;
  dataBuildingList: any;
  dataMasterStatus: any;
  data_device: any;
  spinnerFilterActive = false;
  storedData: any;

  rows: any = [];
  public breadcrumb: any;
  spinnerActive: boolean = false;
  spinnerExportActive: boolean = false;
  spinnerNewDeviceActive: boolean = false;
  newDeviceActive: boolean = false;

  singlebasicSelected: any;

  constructor(
    private modalService: NgbModal,
    private router: Router,
    private monitoringApiService: BuildingService,
    private deviceService: DeviceService,
    private toastr: ToastrService,
    private tableexcelService: TableexcelService
  ) {}

  ngOnInit() {
    this.breadcrumb = {
      mainlabel: "Device",
      links: [
        {
          name: "Home",
          isLink: false,
          link: "/dashboard/sales",
        },
        {
          name: "Device",
          isLink: false,
        },
      ],
    };
    this.storedData = JSON.parse(localStorage.getItem("currentUser"));
    this.buildingSelected = this.storedData.buildingId;

    if (this.newDeviceActive === true) {
    }
    this.fetchData(
      this.buildingSelected,
      this.categorySelected,
      this.statusSelected
    );
    this.summaryDevice(
      this.buildingSelected,
      this.categorySelected,
      this.statusSelected
    );
    this.dataListMaster();
    this.dataListBuilding();
  }

  fetchData(buildingSelected, categorySelected, statusSelected) {
    this.newDeviceActive = false;
    this.buildingSelected = buildingSelected;
    this.deviceService
      .getDeviceData(buildingSelected, categorySelected, statusSelected)
      .subscribe((res) => {
        this.data = res;
        this.filteredRows = this.data.results.data;
        this.data_device = this.filteredRows.map((item) => ({
          buildingName: item.building_name,
          id: item.id,
          name: item.name,
          icon: item.icon,
          watt: item.watt,
          categoryName: item.category_name,
          typeName: item.type_name,
          voltageName: item.voltage_name,
          statusName: item.status_name,
        }));
      });
  }

  summaryDevice(buildingSelected, categorySelected, statusSelected) {
    this.deviceService
      .getDeviceData(buildingSelected, categorySelected, statusSelected)
      .subscribe((res) => {
        this.summaryTotal = res.results.data;
        this.totalOn = res.results.data.filter(
          (row) => row.status_id === 2
        ).length;
        this.totalOff = res.results.data.filter(
          (row) => row.status_id === 3
        ).length;
      });
  }

  newDevice() {
    this.spinnerNewDeviceActive = true;
    this.newDeviceActive = true;
    this.deviceService.getDeviceData(0, 0, 0).subscribe((res) => {
      this.data = res;
      this.filteredRows = this.data.results.data;
      this.spinnerNewDeviceActive = false;
      this.data_device = this.filteredRows.map((item) => ({
        buildingName: item.building_name,
        id: item.id,
        name: item.name,
        icon: item.icon,
        watt: item.watt,
        categoryName: item.category_name,
        typeName: item.type_name,
        voltageName: item.voltage_name,
        statusName: item.status_name,
      }));
    });
  }

  allDevice() {
    this.fetchData(
      this.buildingSelected,
      this.categorySelected,
      this.statusSelected
    );
  }

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

  dataListBuilding() {
    this.monitoringApiService.getBuildingList().subscribe((data) => {
      this.dataBuildingList = data.data.filter((item) => item.statusId === 2);
    });
  }

  doFilter() {
    if (!this.buildingSelected) {
      this.toastr.error("Warning", "Filter Building tidak boleh kosong.", {
        timeOut: 5000,
        closeButton: true,
      });
    } else {
      this.spinnerFilterActive = true;
      this.fetchData(
        this.buildingSelected,
        this.categorySelected,
        this.statusSelected
      );
      setTimeout(() => {
        this.spinnerFilterActive = false;
      }, 3000);
    }
  }

  doCancelFilter() {
    this.storedData = JSON.parse(localStorage.getItem("currentUser"));
    this.buildingSelected = this.storedData.buildingId;
    this.categorySelected = undefined;
    this.statusSelected = undefined;
    this.fetchData(this.buildingSelected, 0, 0);
  }

  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.deviceService.getSyncDeviceData().subscribe((res) => {
      console.log(res);
    });

    setTimeout(() => {
      this.spinnerActive = false;
      this.toastr.success("Success", "Sync Completed.", {
        timeOut: 2000,
        closeButton: true,
      });
      this.fetchData(
        this.buildingSelected,
        this.categorySelected,
        this.statusSelected
      );
    }, 3000);
  }

  exportDevice() {
    this.spinnerExportActive = true;
    setTimeout(() => {
      const columnsToExport = [
        "name",
        "building_name",
        "room_name",
        "watt",
        "category_name",
        "status_name",
        "type_name",
        "voltage_name",
      ];
      this.tableexcelService.exportAsExcelFileDevice(
        this.filteredRows,
        "Smart_building_list_device",
        columnsToExport
      );
      this.spinnerExportActive = false;
    }, 3000);
  }
}
