import { Component, OnDestroy, OnInit } from '@angular/core';
import { YearlyRevenueReportService } from '@fleio-api/reports/yearly-revenue-report.service';
import { Subscription } from 'rxjs';
import { IIcon } from '@shared/ui/common/interfaces/icon';
import { ConfigService } from '@shared/config/config.service';

@Component({
  selector: 'app-yearly-revenue',
  templateUrl: './yearly-revenue.component.html',
  styleUrls: ['./yearly-revenue.component.scss']
})
export class YearlyRevenueComponent implements OnInit, OnDestroy {
  loading = false;
  reportSubscription: Subscription = null;
  report: Array<Record<string, any>>;
  currentDate = new Date();
  currentYear = this.currentDate.getFullYear();
  selectedYear = this.currentYear;

  baseInfoIcon = {
    name: 'info',
    fontSize: '16px',
    height: '17px',
    marginLeft: '5px',
    verticalAlign: 'middle',
  } as IIcon;
  revenueInfoIcon = Object.assign({}, this.baseInfoIcon);
  addCreditInfoIcon = Object.assign({}, this.baseInfoIcon);
  subtractCreditInfoIcon = Object.assign({}, this.baseInfoIcon);
  taxesInfoIcon = Object.assign({}, this.baseInfoIcon);

  constructor(
    private yearlyRevenueReportService: YearlyRevenueReportService,
    public config: ConfigService,
  ) { }

  ngOnInit(): void {
    this.revenueInfoIcon.tooltip = $localize`Total money collected on invoices (including paid from credit balance), except taxes and amounts added to credit balance`;
    this.addCreditInfoIcon.tooltip = $localize`Total amount added to clients' credit balance (via payments, by staff or refunds to credit)`;
    this.subtractCreditInfoIcon.tooltip = $localize`Total amount removed from clients' credit balance (to pay invoices or refunded to credit)`;
    this.taxesInfoIcon.tooltip = $localize`Total taxes from invoices`;
    this.loadReport(this.selectedYear);
  }

  loadReport(forYear=null) {
    this.loading = true;
    this.reportSubscription = this.yearlyRevenueReportService.getYearlyRevenueReport(forYear).subscribe(value => {
      this.report = value.report as Array<Record<string, any>>;
    });
    this.reportSubscription.add(() => {
      this.loading = false;
    });
  }

  ngOnDestroy() {
    if (this.reportSubscription) {
      this.reportSubscription.unsubscribe();
      this.reportSubscription = null;
    }
  }

  htmlToCSV() {
    const data = [];
    const table = document.getElementById('report-table');
    const clonedTable = table.cloneNode(true) as any;
    const infoElements = clonedTable.getElementsByClassName('info-elem');
    while (infoElements.length) {
      infoElements[infoElements.length - 1].remove();
    }
    const rows = clonedTable.querySelectorAll('tr');
    // eslint-disable-next-line @typescript-eslint/prefer-for-of
    for (let i = 0; i < rows.length; i++) {
      const tr = rows[i];
      const row = [];
      const cols = tr.querySelectorAll('td, th');
      const colsArray = Array.from(cols) as any;
      // eslint-disable-next-line @typescript-eslint/prefer-for-of
      for (let j = 0; j < colsArray.length; j++) {
          // @ts-ignore
          row.push(`"${colsArray[j].innerText}"`);
      }
      data.push(row.join(','));
    }
    this.downloadCSVFile(data.join('\n'));
  }

  downloadCSVFile(csv) {
    const csv_file = new Blob([csv], {type: 'text/csv'});
    const download_link = document.createElement('a');
    download_link.download = 'report';
    download_link.href = window.URL.createObjectURL(csv_file);
    download_link.style.display = 'none';
    document.body.appendChild(download_link);
    download_link.click();
  }

  navigateLeft() {
    this.selectedYear -= 1;
    this.loadReport(this.selectedYear);
  }

  navigateRight() {
    this.selectedYear += 1;
    this.loadReport(this.selectedYear);
  }

}
