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";

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

  @BlockUI("zeroConfiguration") blockUIZeroConfiguration: NgBlockUI;

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

  ngOnInit() {
    this.breadcrumb = {
      mainlabel: "Device",
      links: [
        {
          name: "Home",
          isLink: false,
          link: "/dashboard/sales",
        },
        {
          name: "Device",
          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)
    );
  }

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

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

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

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