import { Component, OnInit } from "@angular/core";
import { Router } from "@angular/router";
import { TableApiService } from "src/app/_services/table-api.service";
import { BuildingService } from "../service/monitoring-api.service";
import { DatePipe } from "@angular/common";
import { CostManagementService } from "../service/cost-management.service";
import { NgbModal } from "@ng-bootstrap/ng-bootstrap";
import { ModalAddActualComponent } from "./modal-add-actual/modal-add-actual.component";

import { ChartEvent, ChartType } from "ng-chartist";
import * as Chartist from "chartist";
import "chartist-plugin-tooltips";

@Component({
  selector: "app-cost-management",
  templateUrl: "./cost-management.component.html",
  styleUrls: ["./cost-management.component.css"],
})
export class CostManagementComponent implements OnInit {
  public breadcrumb: any;
  data: any;
  filteredRows: any[];
  data_cost: any;
  searchTerm: string = "";
  kwhTerm: string = "";
  costTerm: string = "";
  rows: any = [];
  dataMasterCategori: any;
  dataBuildingList: any;
  public focucedElement = "";
  spinnerActive = false;
  spinnerActiveActual = false;
  spinnerFilterActive = false;

  donutChart2: any;

  barChart: any;

  dateSelected: any;
  buildingSelected: any;
  categorySelected: any;
  dataComp: any;
  dataCompPrev: any;
  dataCompAct: any;
  storedData: any;

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

  ngOnInit() {
    this.breadcrumb = {
      mainlabel: "Cost Management",
      links: [
        {
          name: "Home",
          isLink: false,
        },
        {
          name: "Cost Management",
          isLink: false,
        },
      ],
    };
    this.storedData = JSON.parse(localStorage.getItem("currentUser"));
    this.buildingSelected = this.storedData.buildingId;
    const currentDate = new Date();
    this.dateSelected = currentDate.toISOString().slice(0, 7);

    this.fetchData(
      this.storedData.buildingId,
      this.dateSelected,
      this.categorySelected
    );
    this.dataListMaster();
    this.dataListBuilding();

    this.dataCompWaterElectCost(this.storedData.buildingId);
    this.dataCompPrevMonthCost(this.storedData.buildingId);
    this.dataCompActEstCost(this.storedData.buildingId);
  }

  fetchData(id, period, category) {
    this.costService
      .getCostManagement(id, period, category)
      .subscribe((response) => {
        this.data = response.results.data;
        this.filteredRows = this.data;
        this.kwhTerm = response.results.kwh;
        this.costTerm = response.results.cost;

        this.data_cost = this.filteredRows.map((item) => ({
          building: item.name,
          categoryName: item.category_name,
          estimationCost: item.estimation_cost,
          totalUse: item.total_use,
          endDate: item.end_date,
          statusId: item.status_id,
        }));
      });
  }

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

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

  dataCompWaterElectCost(buildingId) {
    this.costService.getCompWaterElectCost(buildingId).subscribe((data) => {
      this.dataComp = data.data;
      const dataChart2 = {
        donut: {
          series: [this.dataComp.elect, this.dataComp.water],
          labels: ["Electricity", "Water"],
        },
      };
      this.donutChart2 = {
        type: "Pie",
        data: dataChart2.donut,
        options: {
          chartPadding: 0,
          fullwidth: true,
          height: "150px",
          donut: true,
          showLabel: true,
          startAngle: 0,
          labelPosition: "outside",
          labelOffset: 50,
          plugins: [
            Chartist.plugins.tooltip({
              appendToBody: true,
            }),
          ],
          labelInterpolationFnc: function (value) {
            return value;
          },
        },
      };
    });
  }

  dataCompPrevMonthCost(buildingId) {
    this.costService.getCompPrevMonthCost(buildingId).subscribe((data) => {
      this.dataCompPrev = data.data;
      const randomValue = Math.floor(Math.random() * (100 - 50 + 1)) + 50;
      const dataBar = {
        Bar: {
          labels: [[this.dataCompPrev[0].name], [this.dataCompPrev[1].name]],
          series: [[randomValue], [this.dataCompPrev[1].value]],
        },
      };
      this.barChart = {
        type: "Bar",
        data: dataBar.Bar,
        options: {
          fullwidth: true,
          width: "100px",
          height: "200px",
          seriesBarDistance: 200,
          chartPadding: {bottom: 40 },
          axisX: {
            showGrid: false,
            showLabel: true,
            offset: 30, 
          },
          axisY: {
            showGrid: false,
            showLabel: false, // Hide labels on the y-axis
            scaleMinSpace: 30,
          },
          classNames: {
            bar: "ct-bar", // Add custom class to the bar
          },
        },
        responsiveOptions: [
          [
            "screen and (max-width: 640px)",
            {
              seriesBarDistance: 10,
              axisX: {
                labelInterpolationFnc: function (value) {
                  return value[0]; // Return the first character of the label
                },
              },
            },
          ],
        ],
      };
    });
  }

  dataCompActEstCost(buildingId) {
    this.costService.getCompActEstCost(buildingId).subscribe((data) => {
      this.dataCompAct = data.data[0];
    });
  }

  syncData() {
    const dataDate = {
      buildingId: this.buildingSelected,
      periode: this.dateSelected,
    };
    this.spinnerActive = true;
    this.costService.getSyncCost(dataDate).subscribe((data) => {
      console.log(data);
    });
    setTimeout(() => {
      this.spinnerActive = false;
      this.fetchData(
        this.buildingSelected,
        this.dateSelected,
        this.categorySelected
      );
    }, 3000);
  }

  actualData() {
    this.spinnerActiveActual = true;
    this.costService
      .getRealCostByBuildingId(4, this.dateSelected)
      .subscribe((data) => {
        console.log(data.data[0]);
        // this.costTerm = data.data[0].est_cost
      });
    setTimeout(() => {
      this.spinnerActiveActual = false;
      this.fetchData(
        this.buildingSelected,
        this.dateSelected,
        this.categorySelected
      );
    }, 3000);
  }

  doFilter() {
    const requestData = {
      building: this.buildingSelected,
      category: this.categorySelected,
      date: this.dateSelected,
      searchTerm: this.searchTerm,
    };
    this.spinnerFilterActive = true;
    setTimeout(() => {
      this.spinnerFilterActive = false;
      this.fetchData(
        this.buildingSelected,
        this.dateSelected,
        this.categorySelected
      );
      this.dataCompWaterElectCost(this.buildingSelected);
      this.dataCompPrevMonthCost(this.buildingSelected);
      this.dataCompActEstCost(this.buildingSelected);
    }, 3000);
  }

  addFieldValue() {
    const modalRef = this.modalService.open(ModalAddActualComponent, {
      size: "sm",
    });
    modalRef.componentInstance.newAttribute = {
      id: null,
      name: "",
    };

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

  focusElement(focucedElement: any) {
    this.focucedElement = focucedElement;
  }

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

  viewRow(row) {
    console.log("View row:", row);
    this.router.navigate(["/cost-management/view", row.name]);
  }
}
