import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { DialogsModule } from '@progress/kendo-angular-dialog';
import { InputsModule } from '@progress/kendo-angular-inputs';
import { LabelModule } from '@progress/kendo-angular-label';
import { DropDownsModule } from '@progress/kendo-angular-dropdowns';
import { DateInputsModule } from '@progress/kendo-angular-dateinputs';
import { LayoutModule } from '@progress/kendo-angular-layout';
import { ButtonsModule } from '@progress/kendo-angular-buttons';
import { MemberDto, CreateMemberRequest } from '../../models/member.model';
import { GENDER_OPTIONS, LANGUAGE_OPTIONS, MEMBER_STATUS_OPTIONS } from '../../../../shared/i18n/option-lists';

@Component({
  selector: 'app-member-form-dialog',
  standalone: true,
  imports: [
    CommonModule, ReactiveFormsModule, DialogsModule, InputsModule,
    LabelModule, DropDownsModule, DateInputsModule, LayoutModule, ButtonsModule
  ],
  templateUrl: './member-form-dialog.component.html',
})
export class MemberFormDialogComponent implements OnInit {
  @Input() member: MemberDto | null = null;   // null = create mode
  @Output() saved     = new EventEmitter<CreateMemberRequest>();
  @Output() cancelled = new EventEmitter<void>();

  form!: FormGroup;
  isEditMode = false;

  readonly statusOptions = MEMBER_STATUS_OPTIONS;
  readonly genderOptions = GENDER_OPTIONS;
  readonly langOptions = LANGUAGE_OPTIONS;

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.isEditMode = this.member !== null;
    this.form = this.fb.group({
      // Basic Info
      firstName_en:       [this.member?.firstName_en ?? '', [Validators.required, Validators.maxLength(100)]],
      lastName_en:        [this.member?.lastName_en  ?? '', [Validators.required, Validators.maxLength(100)]],
      nickName:           [this.member?.nickName     ?? null, Validators.maxLength(100)],
      firstName_zh:       [this.member?.firstName_zh ?? null, Validators.maxLength(100)],
      lastName_zh:        [this.member?.lastName_zh  ?? null, Validators.maxLength(100)],
      entity:             [this.member?.entity       ?? null, Validators.maxLength(200)],
      gender:             [this.member?.gender        ?? null],
      dateOfBirth:        [this.member?.dateOfBirth   ?? null],
      status:             [this.member?.status        ?? 'Member', Validators.required],
      languagePreference: [this.member?.languagePreference ?? 'en', Validators.required],
      // Contact
      email:    [this.member?.email    ?? null, [Validators.email, Validators.maxLength(200)]],
      phoneCell:[this.member?.phoneCell ?? null, Validators.maxLength(30)],
      phoneHome:[this.member?.phoneHome ?? null, Validators.maxLength(30)],
      address:  [this.member?.address  ?? null, Validators.maxLength(500)],
      city:     [this.member?.city     ?? null, Validators.maxLength(100)],
      state:    [this.member?.state    ?? null, Validators.maxLength(50)],
      zipCode:  [this.member?.zipCode  ?? null, Validators.maxLength(20)],
      country:  [this.member?.country  ?? 'USA', Validators.maxLength(100)],
      // Church Info
      joinDate:     [this.member?.joinDate     ?? null],
      baptismDate:  [this.member?.baptismDate  ?? null],
      baptismChurch:[this.member?.baptismChurch ?? null, Validators.maxLength(200)],
      notes:        [this.member?.notes        ?? null],
    });
  }

  get title(): string {
    return this.isEditMode ? 'Edit Member' : 'Add Member';
  }

  onSubmit(): void {
    if (this.form.invalid) { this.form.markAllAsTouched(); return; }
    const v = this.form.value;
    const payload: CreateMemberRequest = {
      ...v,
      dateOfBirth: toDateOnlyString(v.dateOfBirth),
      baptismDate: toDateOnlyString(v.baptismDate),
      joinDate:    toDateOnlyString(v.joinDate),
    };
    this.saved.emit(payload);
  }

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

// Kendo DatePicker emits a JS Date; the API expects DateOnly ("yyyy-MM-dd").
// Use local components so the date the user picked isn't shifted by UTC offset.
function toDateOnlyString(d: Date | string | null | undefined): string | null {
  if (d == null || d === '') return null;
  if (typeof d === 'string') return d.length >= 10 ? d.substring(0, 10) : d;
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${day}`;
}
