import { Component, inject, signal } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatChipsModule } from '@angular/material/chips';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatIconModule } from '@angular/material/icon';
import { CashboxExportApi } from '../../../../core/team/cashbox-export-api';
import { RecurringTransactionInterval } from '../../../../models/recurring-transaction.model';

const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

@Component({
  selector: 'app-cashbox-export-subscription-dialog',
  imports: [
    ReactiveFormsModule,
    MatButtonModule,
    MatChipsModule,
    MatDialogModule,
    MatFormFieldModule,
    MatIconModule,
    MatInputModule,
    MatSelectModule,
    MatSlideToggleModule,
  ],
  templateUrl: './cashbox-export-subscription-dialog.html',
  styleUrl: './cashbox-export-subscription-dialog.scss',
})
export class CashboxExportSubscriptionDialog {
  protected readonly dialogRef = inject(MatDialogRef<CashboxExportSubscriptionDialog>);
  private readonly data = inject<{ teamId: number }>(MAT_DIALOG_DATA);
  private readonly formBuilder = inject(FormBuilder);
  private readonly api = inject(CashboxExportApi);

  protected readonly recipients = signal<string[]>([]);
  protected readonly loadError = signal<string | null>(null);
  protected readonly saveError = signal<string | null>(null);
  protected readonly form = this.formBuilder.nonNullable.group({
    interval: ['monthly' as RecurringTransactionInterval, Validators.required],
    active: [false],
  });

  constructor() {
    this.api.getSubscription(this.data.teamId).subscribe({
      next: (subscription) => {
        this.recipients.set(subscription.recipients);
        this.form.setValue({ interval: subscription.interval, active: subscription.active });
      },
      error: () => {
        this.loadError.set('Einstellungen konnten nicht geladen werden.');
      },
    });
  }

  protected addRecipient(value: string): void {
    const trimmed = value.trim();
    if (!EMAIL_PATTERN.test(trimmed) || this.recipients().includes(trimmed)) return;
    this.recipients.set([...this.recipients(), trimmed]);
  }

  protected removeRecipient(value: string): void {
    this.recipients.set(this.recipients().filter((entry) => entry !== value));
  }

  protected save(): void {
    if (this.form.invalid) return;
    this.saveError.set(null);
    const { interval, active } = this.form.getRawValue();
    this.api
      .updateSubscription(this.data.teamId, { recipients: this.recipients(), interval, active })
      .subscribe({
        next: () => this.dialogRef.close(),
        error: () => {
          this.saveError.set('Speichern fehlgeschlagen.');
        },
      });
  }
}
