import { Component, inject, signal } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, ValidationErrors, ValidatorFn, Validators } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { CashboxExportApi } from '../../../../core/team/cashbox-export-api';
import { CashboxExportFormat } from '../../../../models/cashbox-export.model';
import { FileDownloadService } from '../../../../shared/file-download/file-download.service';

const rangeValid: ValidatorFn = (group): ValidationErrors | null => {
  const from = group.get('from')?.value;
  const to = group.get('to')?.value;
  return from && to && from > to ? { rangeInvalid: true } : null;
};

@Component({
  selector: 'app-cashbox-export-dialog',
  imports: [
    ReactiveFormsModule,
    MatButtonModule,
    MatDialogModule,
    MatFormFieldModule,
    MatInputModule,
    MatSelectModule,
  ],
  template: `
    <h2 mat-dialog-title>Kassenbuch exportieren</h2>
    <form [formGroup]="form" (ngSubmit)="download()">
      <mat-dialog-content>
        @if (downloadError()) {
          <p class="error-message" role="alert">{{ downloadError() }}</p>
        }
        <mat-form-field appearance="outline">
          <mat-label>Von</mat-label>
          <input matInput formControlName="from" type="date" />
        </mat-form-field>
        <mat-form-field appearance="outline">
          <mat-label>Bis</mat-label>
          <input matInput formControlName="to" type="date" />
        </mat-form-field>
        <mat-form-field appearance="outline">
          <mat-label>Format</mat-label>
          <mat-select formControlName="format">
            <mat-option value="csv">CSV</mat-option>
            <mat-option value="pdf">PDF</mat-option>
          </mat-select>
        </mat-form-field>
      </mat-dialog-content>
      <mat-dialog-actions align="end">
        <button mat-button type="button" (click)="dialogRef.close()">Abbrechen</button>
        <button mat-flat-button type="submit" [disabled]="form.invalid">Herunterladen</button>
      </mat-dialog-actions>
    </form>
  `,
  styles: `
    .error-message {
      padding: 12px 16px;
      border-radius: 12px;
      color: var(--mat-sys-error);
      background: var(--mat-sys-error-container);
    }
  `,
})
export class CashboxExportDialog {
  protected readonly dialogRef = inject(MatDialogRef<CashboxExportDialog>);
  private readonly data = inject<{ teamId: number }>(MAT_DIALOG_DATA);
  private readonly formBuilder = inject(FormBuilder);
  private readonly api = inject(CashboxExportApi);
  private readonly fileDownload = inject(FileDownloadService);

  protected readonly downloadError = signal<string | null>(null);

  protected readonly form = this.formBuilder.nonNullable.group(
    {
      from: ['', Validators.required],
      to: ['', Validators.required],
      format: ['csv' as CashboxExportFormat, Validators.required],
    },
    { validators: rangeValid },
  );

  protected download(): void {
    if (this.form.invalid) return;
    this.downloadError.set(null);
    const { from, to, format } = this.form.getRawValue();
    this.api.exportCashbox(this.data.teamId, from, to, format).subscribe({
      next: (blob) => {
        this.fileDownload.save(blob, `kassenbuch_${from}_${to}.${format}`);
        this.dialogRef.close();
      },
      error: () => {
        this.downloadError.set('Export konnte nicht heruntergeladen werden.');
      },
    });
  }
}
