import { Component, EventEmitter, Output } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { InputsModule } from '@progress/kendo-angular-inputs';
import { ButtonsModule } from '@progress/kendo-angular-buttons';
import { DialogsModule } from '@progress/kendo-angular-dialog';
import { MemberApiService } from '../../../members/services/member-api.service';
import { CreateMemberRequest, MemberListItemDto } from '../../../members/models/member.model';

@Component({
  selector: 'app-member-quick-add-dialog',
  standalone: true,
  imports: [CommonModule, FormsModule, InputsModule, ButtonsModule, DialogsModule],
  templateUrl: './member-quick-add-dialog.component.html',
})
export class MemberQuickAddDialogComponent {
  @Output() created = new EventEmitter<MemberListItemDto>();
  @Output() cancelled = new EventEmitter<void>();

  firstName_en = '';
  lastName_en = '';
  nickName: string | null = null;
  firstName_zh: string | null = null;
  lastName_zh: string | null = null;
  entity: string | null = null;
  phoneCell: string | null = null;
  saving = false;

  constructor(private memberApi: MemberApiService) {}

  save(): void {
    if (!this.firstName_en || !this.lastName_en) return;
    this.saving = true;
    const req: CreateMemberRequest = {
      firstName_en: this.firstName_en,
      lastName_en: this.lastName_en,
      nickName: this.nickName,
      firstName_zh: this.firstName_zh,
      lastName_zh: this.lastName_zh,
      entity: this.entity,
      gender: null,
      dateOfBirth: null,
      baptismDate: null,
      baptismChurch: null,
      email: null,
      phoneCell: this.phoneCell,
      phoneHome: null,
      address: null,
      city: null,
      state: null,
      zipCode: null,
      country: 'USA',
      status: 'Visitor',
      languagePreference: 'en',
      joinDate: null,
      notes: null,
      familyUnitId: null,
    };
    this.memberApi.create(req).subscribe({
      next: ({ id }) => {
        this.saving = false;
        this.created.emit({
          id,
          firstName_en: this.firstName_en,
          lastName_en: this.lastName_en,
          nickName: this.nickName,
          firstName_zh: this.firstName_zh,
          lastName_zh: this.lastName_zh,
          entity: this.entity,
          status: 'Visitor',
          email: null,
          phoneCell: this.phoneCell,
          joinDate: null,
          linkedUserId: null,
        });
      },
      error: () => { this.saving = false; },
    });
  }
}
