import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { BlockUI, NgBlockUI } from 'ng-block-ui';
import { TableApiService } from 'src/app/_services/table-api.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[];
  searchTerm: string = "";
  rows: any = [];
  @BlockUI("zeroConfiguration") blockUIZeroConfiguration: NgBlockUI;

  constructor(
    private tableApiservice: TableApiService,
    private router: Router
  ) {}

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

  fetchData() {
    this.tableApiservice.getTableInitialisationData().subscribe((response) => {
      this.data = response;
      this.filteredRows = this.data.rows;
    });
  }

  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]);
  }

  editRow(row) {
    console.log("Edit row:", row);
    this.router.navigate(["/cost-management/edit", row.name]);
  }

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

  onTouchStart(event: Event) {
    event.preventDefault(); // Add this if necessary
  }
}
