import { Component, OnInit } from "@angular/core";
import { BuildingService } from "../service/monitoring-api.service";
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 "chartist-plugin-tooltips";
import { ModalExportComponent } from "./modal-export/modal-export.component";
import { TableexcelService } from "src/app/_services/tableexcel.service";

@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;
  barChart: any;

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

  chartOption: any;
  chartOption2: any;

  spinnerExportActive = false;

  constructor(
    private monitoringApiService: BuildingService,
    private costService: CostManagementService,
    private modalService: NgbModal,
    private tableexcelService: TableexcelService
  ) {}

  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.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,
          roomName: item.room_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);
    });
  }

  dataCompPrevMonthCost(buildingId) {
    this.costService.getCompPrevMonthCost(buildingId).subscribe((data) => {
      this.dataCompPrev = data.data;
      this.chartOption = {
        grid: {
          left: "25%",
          right: "25%",
          top: "20%",
          bottom: "20%",
        },

        // Add tooltip
        tooltip: {
          trigger: "axis",
          enterable: false,
          formatter: function (params) {
            return `${params[0].name}<br/>${
              params[0].seriesName
            }: Rp. ${params[0].value.toLocaleString()}`;
          },
        },

        // Add legend
        legend: false,

        // Add custom colors
        color: ["#BEF264"],

        // Horizontal axis
        xAxis: [
          {
            type: "category",
            data: [this.dataCompPrev[0].name, this.dataCompPrev[1].name],
            axisLine: {
              show: true,
              lineStyle: {
                color: "#BEF264",
                width: 4,
              },
            },
            axisTick: {
              show: false,
            },
            splitLine: {
              show: false,
            },
            axisLabel: {
              show: false,
            },
          },
        ],

        // Vertical axis
        yAxis: [
          {
            type: "value",
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            splitLine: {
              show: false,
            },
            axisLabel: {
              show: false,
            },
          },
        ],

        // Add series
        series: [
          {
            name: "Cost",
            type: "bar",
            data: [this.dataCompPrev[0].value, this.dataCompPrev[1].value],
            label: {
              show: true,
              position: "top",
              color: "#ffffff",
              formatter: function (params) {
                return `Rp. ${params.value.toLocaleString()}`;
              },
            },
            barWidth: "50%",
          },
        ],
      };
    });
  }

  dataCompActEstCost(buildingId) {
    this.costService.getCompActEstCost(buildingId).subscribe((data) => {
      this.dataCompAct = data.data[0];
      this.chartOption2 = {
        grid: {
          left: "25%",
          right: "25%",
          top: "20%",
          bottom: "20%",
        },

        // Add tooltip
        tooltip: {
          trigger: "axis",
          enterable: false,
          formatter: function (params) {
            return `${params[0].name}<br/>${
              params[0].seriesName
            }: Rp. ${params[0].value.toLocaleString()}`;
          },
        },

        // Add legend
        legend: false,

        // Add custom colors
        color: ["#BEF264"],

        // Horizontal axis
        xAxis: [
          {
            type: "category",
            data: ["Estimation Cost", "Actual Cost"],
            axisLine: {
              show: true,
              lineStyle: {
                color: "#BEF264",
                width: 4,
              },
            },
            axisTick: {
              show: false,
            },
            splitLine: {
              show: false,
            },
            axisLabel: {
              show: false,
            },
          },
        ],

        // Vertical axis
        yAxis: [
          {
            type: "value",
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            splitLine: {
              show: false,
            },
            axisLabel: {
              show: false,
            },
          },
        ],

        // Add series
        series: [
          {
            name: "Cost",
            type: "bar",
            data: [this.dataCompAct.est_cost, this.dataCompAct.real_cost],
            label: {
              show: true,
              position: "top",
              color: "#ffffff",
              formatter: function (params) {
                return `Rp. ${params.value.toLocaleString()}`;
              },
            },
            barWidth: "50%", // Adjust bar width
          },
        ],
      };
    });
  }

  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",
      centered: true,
    });
    modalRef.componentInstance.buildingId = this.buildingSelected;
    modalRef.componentInstance.periode = this.dateSelected;

    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) {
    const modalRef = this.modalService.open(ModalExportComponent, {
      size: "xl",
      centered: true,
    });
    modalRef.componentInstance.buildingId = this.buildingSelected;
    modalRef.componentInstance.dataRow = row;

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

  export(){
    this.spinnerExportActive = true;
    setTimeout(() => {
      const columnsToExport = [
        "name",
        "room_name",
        "category_name",
        "total_use",
        "estimation_cost",
        "end_date",
      ];
      this.tableexcelService.exportAsExcelFileCostManage(
        this.filteredRows,
        "Smart_building_cost_management",
        columnsToExport
      );
      this.spinnerExportActive = false;
    }, 3000);
  }
}
