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

@Component({
  selector: 'app-logging',
  imports: [ TranslateModule, FormsModule, NgSelectModule, CommonModule, ReactiveFormsModule,
    TableFilterPipe
   ],
  providers: [ DatePipe ],
  templateUrl: './logging.component.html',
  styleUrl: './logging.component.scss'
})
export class LoggingComponent implements OnInit {
  currentPage: number = 1;
  pageSizeOptions = pageSizeOptions
  logsDataExpanded: boolean = true
  itemsPerPage: number = 5;
  searchText: any = '';
  allItems: any[] = [];
  pagedItems: any[] = [];
  logsList: LogsManagementResponse[] = [];
  logsSearchForm!: FormGroup;
  isLoading: boolean = false;

  constructor(
    private fb: FormBuilder,
    private httpService: HttpURIService,
    private datePipe: DatePipe,
    private excelExportServic: ExcelExportService
  ) { }

  ngOnInit() {
    this.initializeLogsSearchForm();
  }

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

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

    let formValues = this.logsSearchForm.value;
    this.isLoading = true;

    let fromDateTransformed = this.datePipe.transform(formValues.fromDate, "dd-MM-yyyy");
    let toDateTransformed = this.datePipe.transform(formValues.toDate, "dd-MM-yyyy");

    const params = new HttpParams()
      .set('fromDate', fromDateTransformed!)
      .set('toDate', toDateTransformed!);

    this.httpService.requestGET<LogsManagementResponse[]>(URIKey.LOGGER_MANAGER_URI, params).subscribe({
      next: (response) => {
        this.logsList = response;
        this.allItems = [...this.logsList];
        this.updatePagedItems();
        this.isLoading = false;
      },
      error: (err) => {
        console.error('Error fetching logging details data:', err);
        this.logsList = [];
        this.isLoading = false;
      }
    });
  }

  updatePagedItems(): void {
    const startIndex = (this.currentPage - 1) * this.itemsPerPage;
    const endIndex = startIndex + this.itemsPerPage;
    this.pagedItems = this.allItems.slice(startIndex, endIndex);
  }

  totalPages(): number {
    return Math.ceil(this.allItems.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(){
    this.logsDataExpanded = !this.logsDataExpanded;
  }

  exportDataInExcel(){
    this.excelExportServic.exportExcel(this.logsList, LOGGING_DETAILS_FILE_NAME)
  }

}
