import { Component, Input, OnInit, OnChanges, SimpleChanges, ChangeDetectorRef } from '@angular/core';
import { CommonModule, CurrencyPipe, DatePipe } from '@angular/common';
import { Observable, BehaviorSubject, switchMap, tap, catchError, of } from 'rxjs';

import { AccountPayableService } from '../../services/accountpayable.service';
import { AccountPayable, AccountPayableItem } from '../../interfaces/accountpayable.interface';
import { DataTableComponent, Column } from '../../../../../shared/components/data-table/data-table.component';

@Component({
  selector: 'app-account-payable-items',
  standalone: true,
  imports: [CommonModule, DataTableComponent],
  providers: [CurrencyPipe, DatePipe],
  templateUrl: './account-payable-items.component.html',
  styleUrl: './account-payable-items.component.scss'
})
export class AccountPayableItemsComponent implements OnInit {
  @Input() accountPayableData: AccountPayable | undefined;
  items$: Observable<AccountPayableItem[]>;
  loading = false;
  hasError = false;
  
  private accountIdSubject = new BehaviorSubject<string | null>(null);
  private _initialData: AccountPayable | undefined;
  
  @Input() set initialData(data: AccountPayable | undefined) {
    this._initialData = data;
  }
  

  columns: Column[] = [
    { field: "id", 
      header: "ID", sortable: true, 
      filterable: false 
    },
    { field: "code", 
      header: "Código", sortable: true, 
      filterable: false 
    },
    {
      field: "value",
      header: "Valor Original",
      sortable: true,
      filterable: false,
      label: (value: number) => this.currencyPipe.transform(value, 'BRL', 'symbol', '1.2-2') || "-"
    },
    {
      field: "discount",
      header: "Desconto",
      sortable: true,
      filterable: false,
      label: (value: number) => {
        if (!value || value === 0) return "-";
        return `- ${this.currencyPipe.transform(value, 'BRL', 'symbol', '1.2-2')}`;
      }
    },
    {
      field: "addition",
      header: "Acréscimo",
      sortable: true,
      filterable: false,
      label: (value: number) => {
        if (!value || value === 0) return "-";
        return `+ ${this.currencyPipe.transform(value, 'BRL', 'symbol', '1.2-2')}`;
      }
    },
    {
      field: "total",
      header: "Valor Final",
      sortable: true,
      filterable: false,
      label: (value: number) => this.currencyPipe.transform(value, 'BRL', 'symbol', '1.2-2') || "-"
    },
    {
      field: "status",
      header: "Status",
      sortable: true,
      filterable: false,
      allowHtml: true,
      label: (status: string) => {
        const statusConfig: { [key: string]: { label: string, class: string } } = {          
          'pending': { label: 'Pendente', class: 'status-pending' },
          'paid': { label: 'Pago', class: 'status-paid' },
          'approved': { label: 'Aprovado', class: 'status-approved' },
          'approvedCustomer': { label: 'Aprovado pelo Cliente', class: 'status-approved-customer' },
          'refused': { label: 'Recusado', class: 'status-refused' },
          'cancelled': { label: 'Cancelado', class: 'status-cancelled' }
        };
        
        const config = statusConfig[status] || { label: status, class: 'status-unknown' };
        return `<span class="status-badge ${config.class}">${config.label}</span>`;
      }
    },
    {
      field: "paidAt",
      header: "Data Pagamento",
      sortable: true,
      filterable: false,
      label: (date: string | null) => {
        if (!date) return "-";
        return this.datePipe.transform(date, "dd/MM/yyyy") || "-";
      }
    },
    { field: "notes", header: "Observações", sortable: false, filterable: false }
  ];

  constructor(
    private accountPayableService: AccountPayableService,
    private currencyPipe: CurrencyPipe,
    private datePipe: DatePipe,
    private cdr: ChangeDetectorRef
  ) {
    
    
    this.items$ = this.accountIdSubject.pipe(
      switchMap(id => {        
        if (!id) {
          return of([]);
        }

        this.loading = true;
        this.hasError = false;
        this.cdr.detectChanges();

        return this.accountPayableService.getAccountPayableItems(id).pipe(
          tap((items) => {
            this.loading = false;
            this.hasError = false;
          }),
          catchError(error => {
            this.loading = false;
            this.hasError = true;
            this.cdr.detectChanges();
            return of([]);
          })
        );
      })
    );
  }

  ngOnInit(): void {
    this.accountIdSubject.next(this._initialData?.id ? this._initialData?.id : null);
  }
  

  getTotalValue(items: AccountPayableItem[]): number {
    if (!items || items.length === 0) return 0;
    return items.reduce((sum, item) => sum + (item.total || 0), 0);
  }
  getItemCount(items: AccountPayableItem[]): number {
    return items ? items.length : 0;
  }
  getDiscountValue(items: AccountPayableItem[]): number {
    if (!items || items.length === 0) return 0;
    return items.reduce((sum, item) => sum + (item.discount || 0), 0);
  }
} 