import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { GridModule, PageChangeEvent } from '@progress/kendo-angular-grid';
import { ButtonsModule } from '@progress/kendo-angular-buttons';
import { DropDownsModule } from '@progress/kendo-angular-dropdowns';
import { InputsModule } from '@progress/kendo-angular-inputs';
import { DateInputsModule } from '@progress/kendo-angular-dateinputs';
import { DialogsModule } from '@progress/kendo-angular-dialog';
import { LOG_LEVEL_OPTIONS } from '../../../../shared/i18n/option-lists';
import { LoggingApiService } from '../../services/logging-api.service';
import { SystemLogListItem, SystemLogDetail, SystemLogQuery } from '../../models/logging.model';

@Component({
  selector: 'app-system-logs-page',
  standalone: true,
  imports: [
    CommonModule, FormsModule, GridModule, ButtonsModule,
    DropDownsModule, InputsModule, DateInputsModule, DialogsModule,
  ],
  templateUrl: './system-logs-page.component.html',
  styleUrls: ['./system-logs-page.component.scss'],
})
export class SystemLogsPageComponent implements OnInit {
  rows: SystemLogListItem[] = [];
  total = 0;
  page = 1;
  pageSize = 20;
  loading = false;

  readonly levels = LOG_LEVEL_OPTIONS;

  // UI-bound filter state; dates are Date objects converted to yyyy-MM-dd on send.
  minLevel: string | null = null;
  search = '';
  from: Date | null = null;
  to: Date | null = null;

  detail: SystemLogDetail | null = null;

  constructor(private api: LoggingApiService) {}

  ngOnInit(): void { this.load(); }

  load(): void {
    this.loading = true;
    const query: SystemLogQuery = {
      page: this.page,
      pageSize: this.pageSize,
      minLevel: this.minLevel ?? undefined,
      search: this.search || undefined,
      from: this.toLocalDate(this.from),
      to: this.toLocalDate(this.to),
    };
    this.api.getSystemLogs(query).subscribe({
      next: r => { this.rows = r.items; this.total = r.totalCount; this.loading = false; },
      error: () => (this.loading = false),
    });
  }

  get skip(): number { return (this.page - 1) * this.pageSize; }
  applyFilter(): void { this.page = 1; this.load(); }
  onPageChange(e: PageChangeEvent): void { this.page = Math.floor(e.skip / this.pageSize) + 1; this.load(); }

  view(row: SystemLogListItem): void {
    this.api.getSystemLog(row.id).subscribe(d => (this.detail = d));
  }

  levelClass(level: string): string {
    return 'log-level log-level--' + level.toLowerCase();
  }

  /** Local yyyy-MM-dd (never toISOString — that shifts the day by timezone). */
  private toLocalDate(d: Date | null): string | undefined {
    if (!d) return undefined;
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${y}-${m}-${day}`;
  }
}
