import { Component, Input, Output, EventEmitter, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { firstValueFrom } from 'rxjs';
import { DialogsModule } from '@progress/kendo-angular-dialog';
import { InputsModule } from '@progress/kendo-angular-inputs';
import { LabelModule } from '@progress/kendo-angular-label';
import { ButtonsModule } from '@progress/kendo-angular-buttons';
import { MemberListItemDto, memberDisplayName } from '../../models/member.model';
import { ApiConfigService } from '../../../../core/services/api-config.service';
import { ToastService } from '../../../../core/services/toast.service';

interface NotificationResult {
  sentCount: number;
  failedCount: number;
}

/**
 * Admin test action: compose a Web Push message and send it to a single member's devices. Used to
 * verify one-to-one push delivery. Reports clearly when the member has no active subscription.
 */
@Component({
  selector: 'app-send-push-dialog',
  standalone: true,
  imports: [
    CommonModule, ReactiveFormsModule, DialogsModule, InputsModule, LabelModule, ButtonsModule,
  ],
  template: `
<kendo-dialog title="Send Push Notification" (close)="onClose()" [width]="520" [maxWidth]="'95vw'">
  <p class="k-mb-3">
    Send a push notification to <strong>{{ memberName }}</strong>.
    They must have enabled notifications on a device first.
  </p>

  <form [formGroup]="form" class="k-form k-form-vertical">
    <kendo-formfield>
      <kendo-label text="Title *"></kendo-label>
      <kendo-textbox formControlName="title" [maxlength]="100"></kendo-textbox>
      <kendo-formerror *ngIf="form.get('title')?.errors?.['required']">Required.</kendo-formerror>
    </kendo-formfield>

    <kendo-formfield>
      <kendo-label text="Message *"></kendo-label>
      <kendo-textarea formControlName="body" [rows]="3" resizable="vertical"></kendo-textarea>
      <kendo-formerror *ngIf="form.get('body')?.errors?.['required']">Required.</kendo-formerror>
    </kendo-formfield>
  </form>

  <kendo-dialog-actions>
    <button kendoButton (click)="onClose()">Cancel</button>
    <button kendoButton themeColor="primary" [disabled]="form.invalid || sending" (click)="send()">
      Send
    </button>
  </kendo-dialog-actions>
</kendo-dialog>
  `,
})
export class SendPushDialogComponent implements OnInit {
  @Input({ required: true }) member!: MemberListItemDto;
  @Output() cancelled = new EventEmitter<void>();

  private readonly fb = inject(FormBuilder);
  private readonly http = inject(HttpClient);
  private readonly api = inject(ApiConfigService);
  private readonly toast = inject(ToastService);

  form!: FormGroup;
  sending = false;

  get memberName(): string { return memberDisplayName(this.member); }

  ngOnInit(): void {
    this.form = this.fb.group({
      title: ['River of Life', [Validators.required]],
      body: ['', [Validators.required]],
    });
  }

  async send(): Promise<void> {
    if (this.form.invalid) { this.form.markAllAsTouched(); return; }

    this.sending = true;
    try {
      const result = await firstValueFrom(
        this.http.post<NotificationResult>(this.api.getApiUrl('notifications/send-webpush'), {
          memberIds: [this.member.id],
          title: this.form.value.title,
          body: this.form.value.body,
        }),
      );

      if (result.sentCount > 0) {
        this.toast.success(`已送出 ${result.sentCount} 則推播給 ${this.memberName}。`);
        this.onClose();
      } else {
        this.toast.error(`${this.memberName} 尚未在任何裝置啟用推播，無法送達。`);
      }
    } catch (err: unknown) {
      const message = (err as { error?: { message?: string } })?.error?.message;
      this.toast.error(message ?? '送出推播失敗。');
    } finally {
      this.sending = false;
    }
  }

  onClose(): void {
    this.cancelled.emit();
  }
}
