import { ChangeDetectionStrategy, Component, inject, signal, input, output } from '@angular/core';
import { catchError, debounceTime, distinctUntilChanged, retry, switchMap, tap } from 'rxjs/operators';
import { BehaviorSubject, Observable, Subject } from 'rxjs';
import { GasSnapshotLinesService } from './gas-snapshot-lines.service';
import { InvoiceGasLineItem } from './models/InvoiceGasLineItem';
import { MessageService } from '../_shared/services/message.service';
import * as util from '../_shared/utils/util';
import { FAST_KENDO_COMMON, FAST_PAGE_COMMON } from '../app.config';
import { CurrencyPipe, DecimalPipe } from '@angular/common';

@Component({
  imports: [FAST_KENDO_COMMON, FAST_PAGE_COMMON, DecimalPipe, CurrencyPipe],
  selector: 'gas-snapshot-lines',
  templateUrl: './gas-snapshot-lines.component.html',
  styles: ``,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class GasSnapshotLinesComponent {
  service = inject(GasSnapshotLinesService);
  messageService = inject(MessageService);

  invoiceId = input.required<number>();
  invoiceNum = input<string>();
  closed = output();
  totalAmount = signal<number>(0);
  totalQuantity = signal<number>(0);

  lines = signal<InvoiceGasLineItem[]>([]);
  gridLoading$ = new BehaviorSubject<boolean>(true);
  refreshItems$ = new BehaviorSubject<string>(null);
  items$: Observable<InvoiceGasLineItem[]>;

  // Dynamic column width support
  minimumDynamicColWidth = 150;
  colWidths = {
    lineNum: 35,
    trader: 65,
    dealNum: 115,
    flowDays: 70,
    deliveryPipeline: this.minimumDynamicColWidth,
    deliveryMeter: this.minimumDynamicColWidth,
    quantity: 80,
    price: 80,
    adder: 85,
    invoicePrice: 75,
    amount: 95,
  };
  totalMinColWidths = Object.values(this.colWidths).reduce((a, b) => a + b, 0);

  dynamicColumnWidth$: Observable<number>;
  refreshDynamicColumnWidth$ = new Subject<void>();

  constructor() {
    this.items$ = this.refreshItems$.pipe(
      tap(() => {
        this.gridLoading$.next(true);
      }),
      switchMap(() => {
        const items = this.service.getSnapshotLines(this.invoiceId());
        return items;
      }),
      tap((items) => {
        this.totalQuantity.set(items.reduce((sum, item) => sum + (item.quantity ?? 0), 0));
        this.totalAmount.set(items.reduce((sum, item) => sum + (item.amount ?? 0), 0));
        this.setDynamicColumnWidth();
      }),
      tap(() => {
        this.gridLoading$.next(false);
      }),
      catchError(err => {
        this.gridLoading$.next(false);
        return util.handleError(err, this.messageService);
      }),
      retry(10)
    );

    this.dynamicColumnWidth$ = this.refreshDynamicColumnWidth$.pipe(
      debounceTime(150),
      switchMap(() => {
        return new Observable<number>(subscriber => {
          requestAnimationFrame(() => {
            const winElem = document.querySelector('gas-snapshot-lines fast-window dialog') as HTMLElement;
            const winWidth = winElem?.offsetWidth ?? 0;

            let columnWidth: number;
            if (winWidth > this.totalMinColWidths)
              columnWidth = null; // Return null to auto-size the column
            else
              columnWidth = this.minimumDynamicColWidth;

            subscriber.next(columnWidth);
            subscriber.complete();
          });
        });
      }),
      distinctUntilChanged()
    );
  }

  setDynamicColumnWidth(): void {
    this.refreshDynamicColumnWidth$.next();
  }

  protected closedClicked(): void {
    this.closed.emit();
  }
}

