import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ButtonsModule } from '@progress/kendo-angular-buttons';
import { InputsModule } from '@progress/kendo-angular-inputs';
import { SettingsApiService } from '../../services/settings-api.service';
import {
  NotificationSettingDto, UpdateNotificationSettingRequest, NotificationResult,
} from '../../models/settings.model';

@Component({
  selector: 'app-notification-settings-tab',
  standalone: true,
  imports: [CommonModule, FormsModule, ButtonsModule, InputsModule],
  templateUrl: './notification-settings-tab.component.html',
})
export class NotificationSettingsTabComponent implements OnInit {
  model: NotificationSettingDto | null = null;
  saving = false;
  savedMsg = '';

  // Write-only secret inputs — blank means "keep the stored value".
  smtpPassword = '';
  lineToken = '';
  lineSecret = '';

  // Test-send state.
  testEmailTo = '';
  testEmailMsg = '';
  testingEmail = false;

  testLineMemberId: number | null = null;
  testLineGroupId: number | null = null;
  testLineMsg = '';
  testingLine = false;

  constructor(private api: SettingsApiService) {}

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

  private load(): void {
    this.api.getNotification().subscribe(n => (this.model = n));
  }

  save(): void {
    if (!this.model || this.saving) return;
    this.saving = true;
    this.savedMsg = '';
    const m = this.model;
    const request: UpdateNotificationSettingRequest = {
      enableEmail: m.enableEmail,
      smtpHost:    m.smtpHost,
      smtpPort:    m.smtpPort,
      smtpUseSsl:  m.smtpUseSsl,
      smtpUser:    m.smtpUser,
      fromAddress: m.fromAddress,
      fromName:    m.fromName,
      smtpPassword: this.smtpPassword || null,
      enableLine:  m.enableLine,
      lineChannelAccessToken: this.lineToken || null,
      lineChannelSecret:      this.lineSecret || null,
    };
    this.api.updateNotification(request).subscribe({
      next: () => {
        this.saving = false;
        this.savedMsg = 'Saved / 已儲存';
        // Clear secret inputs and refresh the "configured" flags.
        this.smtpPassword = this.lineToken = this.lineSecret = '';
        this.load();
      },
      error: () => { this.saving = false; },
    });
  }

  sendTestEmail(): void {
    if (this.testingEmail) return;
    this.testingEmail = true;
    this.testEmailMsg = '';
    this.api.testEmail({ toAddress: this.testEmailTo || null }).subscribe({
      next: result => { this.testingEmail = false; this.testEmailMsg = this.describe(result); },
      error: err => { this.testingEmail = false; this.testEmailMsg = this.errorText(err); },
    });
  }

  sendTestLine(): void {
    if (this.testingLine) return;
    this.testingLine = true;
    this.testLineMsg = '';
    this.api.testLine({ memberId: this.testLineMemberId, groupId: this.testLineGroupId }).subscribe({
      next: result => { this.testingLine = false; this.testLineMsg = this.describe(result); },
      error: err => { this.testingLine = false; this.testLineMsg = this.errorText(err); },
    });
  }

  private describe(result: NotificationResult): string {
    if (result.failedCount > 0)
      return `Failed / 失敗：${result.failures.map(f => f.error).join('; ')}`;
    return result.sentCount > 0 ? 'Sent ✓ / 已發送' : 'Nothing sent / 未發送';
  }

  private errorText(err: { error?: { message?: string } }): string {
    return err?.error?.message ?? 'Failed / 失敗';
  }
}
