import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
import { Player } from 'src/app/model';
import { Team } from 'src/app/modules/teams/model/team';
import { TransactionFormComponent } from '../components/transaction-form/transaction-form.component';
import { TransactionType } from './model/transaction-type.enum';
import { CommonModule } from '@angular/common';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatButtonModule } from '@angular/material/button';
import { ConfirmDialogComponent } from '../confirm-dialog/confirm-dialog.component';

const HIGH_AMOUNT_CONFIRM_THRESHOLD = 300;

@Component({
  selector: 'app-new-transaction',
  templateUrl: './new-transaction.component.html',
  styleUrls: ['./new-transaction.component.scss'],
  standalone: true,
  imports: [
    CommonModule
    , TransactionFormComponent
    , MatButtonModule
    , MatDialogModule
  ]
})
export class NewTransactionDialogComponent implements OnInit {
  
  @ViewChild('formComponent') formComponent!: TransactionFormComponent;


  selectedTransactionType: number | null = null;

  isTotal: boolean = false;

  constructor(
    public dialogRef: MatDialogRef<NewTransactionDialogComponent>,
    private dialog: MatDialog,
    @Inject(MAT_DIALOG_DATA) public data: DialogData,
  ) {}

  ngOnInit(): void {
  }


  close() {
    this.dialogRef.close();
  }

  create() {

    const value = this.formComponent.form.value;
    if (!value || value.amount == null || value.total == null || value.type == null) { return; }
    let amount = value.total ? value.amount / this.data.players.length : value.amount;
    amount = Math.round(amount * 100) / 100;

    let res: Transaction[] = [];
    for (let p of this.data.players) {
      res.push({
        amount,
        playerId: p.id,
        type: value.type as any,
        note: value.note as any
      })


    }

    if (value.amount >= HIGH_AMOUNT_CONFIRM_THRESHOLD) {
      const confirmRef = this.dialog.open(ConfirmDialogComponent, {
        data: {
          title: 'Betrag prüfen',
          message: `Es wird${this.data.players.length > 1 ? ' für jede:n der ' + this.data.players.length + ' gewählten Spieler:innen' : ''} ein Betrag von ${value.amount} € gebucht. Bitte kurz prüfen, bevor du fortfährst.`,
          confirmLabel: 'Buchen'
        }
      });

      confirmRef.afterClosed().subscribe(confirmed => {
        if (confirmed) {
          this.dialogRef.close(res);
        }
      });
      return;
    }

    this.dialogRef.close(res);

  }

  get amount(): number {
    const value = this.formComponent?.form?.value;
    if (!value || value.amount == null) { return 0; }
    return Math.round((value.total ? value.amount / this.data.players.length : value.amount) * 100) / 100;
  }

  get transactionType(): string {
    if (this.formComponent?.form?.value?.type == null) { return ''; }
    return this.formComponent.transactionType(this.formComponent.form.value.type);
  }

  get formValid(): boolean {
    return this.formComponent?.form != null && this.formComponent.form.valid;
  }

}


interface DialogData {
  team: Team,
  players: Player[];
  all?: boolean;
}

export interface Transaction {
  playerId: Number;
  amount: number;
  type: TransactionType;
  note: string;
}