import { CommonModule } from '@angular/common';
import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatPaginator, MatPaginatorModule } from '@angular/material/paginator';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MatSort, MatSortModule } from '@angular/material/sort';
import { MatTableDataSource, MatTableModule } from '@angular/material/table';
import { MatTooltipModule } from '@angular/material/tooltip';
import { Transaction } from 'src/app/model';
import { TeamsService } from 'src/app/modules/teams/teams.service';
import { ConfirmDialogComponent } from '../confirm-dialog/confirm-dialog.component';

@Component({
  selector: 'app-show-team-transactions',
  templateUrl: './show-team-transactions.component.html',
  styleUrls: ['./show-team-transactions.component.scss'],
  standalone: true,
  imports: [ CommonModule, MatDialogModule, MatTableModule, MatSortModule, MatPaginatorModule, MatFormFieldModule, MatInputModule, MatProgressSpinnerModule, MatButtonModule, MatIconModule, MatTooltipModule ]
})
export class ShowTeamTransactionsComponent implements OnInit {

  isLoading: boolean = true;
  loadError: boolean = false;

  displayedColumns: string[] = ['amount', 'date', 'type', 'playerName', 'actions'];
  dataSource: MatTableDataSource<Transaction> = new MatTableDataSource<Transaction>([]);

  private paginator?: MatPaginator;
  private sort?: MatSort;

  @ViewChild(MatPaginator)
  set matPaginator(paginator: MatPaginator | undefined) {
    this.paginator = paginator;
    if (paginator) {
      this.dataSource.paginator = paginator;
    }
  }

  @ViewChild(MatSort)
  set matSort(sort: MatSort | undefined) {
    this.sort = sort;
    if (sort) {
      this.dataSource.sort = sort;
    }
  }
  constructor(private teamService: TeamsService,
    private dialog: MatDialog,
    private snackBar: MatSnackBar,
    @Inject(MAT_DIALOG_DATA) public data: DialogData,) {}

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

  load(): void {
    this.isLoading = true;
    this.loadError = false;
    this.teamService.loadTeamsTransactions(this.data.id).subscribe({
      next: data => {
        this.setupData(data);
      },
      error: () => {
        this.isLoading = false;
        this.loadError = true;
      }
    })
  }

  setupData(data: Transaction[]) {
    this.isLoading = false;
    this.dataSource = new MatTableDataSource<Transaction>(data);

    if (this.paginator) {
      this.dataSource.paginator = this.paginator;
    }
    if (this.sort) {
      this.dataSource.sort = this.sort;
    }
  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();

    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

  reverseTransaction(transaction: Transaction) {
    if (transaction.isTeamWalletTransaction || transaction.note?.startsWith('Stornierung von Buchung #')) {
      return;
    }

    const confirmRef = this.dialog.open(ConfirmDialogComponent, {
      data: {
        title: 'Buchung stornieren',
        message: `Buchung über ${transaction.amount} € (${transaction.playerName}, ${transaction.type}) wirklich stornieren? Es wird eine Ausgleichsbuchung erstellt, die Originalbuchung bleibt sichtbar.`,
        confirmLabel: 'Stornieren'
      }
    });

    confirmRef.afterClosed().subscribe(confirmed => {
      if (!confirmed) { return; }

      this.teamService.reverseTransaction(transaction.id).subscribe({
        next: () => {
          this.snackBar.open('Buchung wurde storniert', undefined, { duration: 5000 });
          this.load();
        },
        error: (err) => {
          const message = err?.error?.message || 'Buchung konnte nicht storniert werden';
          this.snackBar.open(message, undefined, { duration: 5000, panelClass: 'snackbar_error' });
        }
      });
    });
  }

  toggleNote() {
    const index = this.displayedColumns.indexOf('note');
    if (index != -1) {
      this.displayedColumns = this.displayedColumns.filter(column => column !== 'note');
    } else {
      this.displayedColumns = [...this.displayedColumns, 'note'];
    }
  }

}

interface DialogData {
  id: number;
}
