import { Component, OnInit } from '@angular/core';
import { CommonModule, DatePipe } from '@angular/common';
import { TranslateModule } from '@ngx-translate/core';
import { ExcelExportService } from '../shared/services/excel-export.service';
import { toDateAfterFromDateValidator, TRANSACTION_LOGS_FILE_NAME } from '../utils/app.constants';
import { pageSizeOptions } from '../utils/app.constants';
import { NgSelectModule } from '@ng-select/ng-select';
import { FormBuilder, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { TableFilterPipe } from '../shared/pipes/table-filter.pipe';
import { TransactionLog } from "../models/user";
import { URIKey } from '../utils/uri-enums';
import { HttpParams } from '@angular/common/http';
import { HttpURIService } from '../app.http.uri.service';

@Component({
  selector: 'app-transaction-logs',
  templateUrl: './transaction-logs.component.html',
  styleUrls: ['./transaction-logs.component.scss'],
imports: [
    TranslateModule,
    FormsModule,
    NgSelectModule,
    CommonModule,
    ReactiveFormsModule,
    TableFilterPipe
  ],
  providers: [DatePipe]})
export class TransactionLogsComponent implements OnInit {
  logsSearchForm!: FormGroup;

  pageSizeOptions = pageSizeOptions;
  itemsPerPage = 10;
  currentPage = 1;
  maxDate: string;
  searchText = '';

  logsDataExpanded = true;
  isLoading = false;

  /** DATA LAYERS (do not mix these) */
  allItems: TransactionLog[] = []; // raw API data
  filteredItems: TransactionLog[] = []; // after search
  pagedItems: TransactionLog[] = []; // table view

  constructor(
    private fb: FormBuilder,
    private httpService: HttpURIService,
    private datePipe: DatePipe,
    private excelExportService: ExcelExportService,
  ) {
    this.maxDate = new Date().toISOString().split('T')[0];
  }

  ngOnInit(): void {
    this.logsSearchForm = this.fb.group(
      {
        fromDate: ['', Validators.required],
        toDate: ['', Validators.required],
      },
      { validators: toDateAfterFromDateValidator },
    );
  }

  getlogsData(): void {
    if (this.logsSearchForm.invalid) return;

    this.isLoading = true;

    const { fromDate, toDate } = this.logsSearchForm.value;

    const params = new HttpParams()
      .set('fromDate', this.datePipe.transform(fromDate, 'dd-MM-yyyy')!)
      .set('toDate', this.datePipe.transform(toDate, 'dd-MM-yyyy')!);

    this.httpService
      .requestGET<TransactionLog[]>(URIKey.TRANSACTION_LOGS, params)
      .subscribe({
        next: (response) => {
          this.allItems = response ?? [];
          this.filteredItems = [...this.allItems];
          this.currentPage = 1;
          this.updatePagedItems();
          this.isLoading = false;
        },
        error: () => {
          this.allItems = [];
          this.filteredItems = [];
          this.pagedItems = [];
          this.isLoading = false;
        },
      });
  }

  /** SEARCH — filters DATA, not DOM */
  applySearch(): void {
    const value = this.searchText.toLowerCase().trim();

    if (!value) {
      this.filteredItems = [...this.allItems];
    } else {
      this.filteredItems = this.allItems.filter((item) =>
        [
          'logId',
          'porOrgacode',
          'transactionID',
          'drMbmbkmsnumber',
          'crMbmbkmsnumber',
          'crPcaglacode',
          'drPcaGlacode',
          'amount',
          'paymentMode',
          'ppmPymdcode',
          'sgtGntrdate',
          'channelCode',
          'createdAt',
          'transactionUri',
          'transactionCode',
        ].some((key) =>
          String((item as any)[key] ?? '')
            .toLowerCase()
            .includes(value),
        ),
      );
    }

    this.currentPage = 1;
    this.updatePagedItems();
  }

  updatePagedItems(): void {
    const start = (this.currentPage - 1) * this.itemsPerPage;
    const end = start + this.itemsPerPage;
    this.pagedItems = this.filteredItems.slice(start, end);
  }

  totalPages(): number {
    return Math.ceil(this.filteredItems.length / this.itemsPerPage);
  }

  previousPage(): void {
    if (this.currentPage > 1) {
      this.currentPage--;
      this.updatePagedItems();
    }
  }

  nextPage(): void {
    if (this.currentPage < this.totalPages()) {
      this.currentPage++;
      this.updatePagedItems();
    }
  }

  itemsPerPageChanged(): void {
    this.currentPage = 1;
    this.updatePagedItems();
  }

  toggleTableCard(): void {
    this.logsDataExpanded = !this.logsDataExpanded;
  }

  exportDataInExcel(): void {
    this.excelExportService.exportExcel(
      this.allItems,    
      TRANSACTION_LOGS_FILE_NAME,
    );
  }


}