import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { GridModule, PageChangeEvent } from '@progress/kendo-angular-grid';
import { InputsModule } from '@progress/kendo-angular-inputs';
import { ButtonsModule } from '@progress/kendo-angular-buttons';
import { IndicatorsModule } from '@progress/kendo-angular-indicators';
import { DropDownsModule } from '@progress/kendo-angular-dropdowns';
import { MemberApiService } from '../../services/member-api.service';
import { MemberFormDialogComponent } from '../../components/member-form-dialog/member-form-dialog.component';
import { CreateUserDialogComponent } from '../../components/create-user-dialog/create-user-dialog.component';
import { InvitationDialogComponent } from '../../components/invitation-dialog/invitation-dialog.component';
import { SendPushDialogComponent } from '../../components/send-push-dialog/send-push-dialog.component';
import {
  MemberListItemDto, MemberDto, CreateMemberRequest,
  PagedResult, memberDisplayName
} from '../../models/member.model';
import { MEMBER_STATUS_OPTIONS } from '../../../../shared/i18n/option-lists';
import { PageHeaderActionsDirective } from '../../../../shared/directives/page-header-actions.directive';
import { HasPermissionDirective } from '../../../../core/directives/has-permission.directive';

@Component({
  selector: 'app-members-page',
  standalone: true,
  imports: [
    CommonModule, FormsModule, GridModule, InputsModule,
    ButtonsModule, IndicatorsModule, DropDownsModule,
    MemberFormDialogComponent, CreateUserDialogComponent, InvitationDialogComponent,
    SendPushDialogComponent,
    PageHeaderActionsDirective, HasPermissionDirective,
  ],
  templateUrl: './members-page.component.html',
  styleUrls: ['./members-page.component.scss'],
})
export class MembersPageComponent implements OnInit {
  // Grid state
  data: MemberListItemDto[] = [];
  totalCount = 0;
  page = 1;
  pageSize = 20;
  isLoading = false;

  // Filters
  searchText = '';
  filterStatus = '';
  readonly statusOptions = [
    { value: '', label: 'All Status/全部狀態' },
    ...MEMBER_STATUS_OPTIONS,
  ];

  // Dialogs
  showMemberDialog = false;
  showCreateUserDialog = false;
  showInviteDialog = false;
  showPushDialog = false;
  editingMember: MemberDto | null = null;
  selectedMemberForUser: MemberListItemDto | null = null;
  selectedMemberForInvite: MemberListItemDto | null = null;
  selectedMemberForPush: MemberListItemDto | null = null;

  readonly memberDisplayName = memberDisplayName;

  constructor(private memberApi: MemberApiService) {}

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

  loadData(): void {
    this.isLoading = true;
    this.memberApi.getPaged({
      page: this.page,
      pageSize: this.pageSize,
      search: this.searchText || undefined,
      status: this.filterStatus || undefined,
    }).subscribe({
      next: (result: PagedResult<MemberListItemDto>) => {
        this.data       = result.items;
        this.totalCount = result.totalCount;
        this.isLoading  = false;
      },
      error: () => { this.isLoading = false; }
    });
  }

  onPageChange(event: PageChangeEvent): void {
    this.page     = event.skip / this.pageSize + 1;
    this.pageSize = event.take;
    this.loadData();
  }

  onSearch(): void {
    this.page = 1;
    this.loadData();
  }

  // ── Member CRUD ─────────────────────────────────────────────────────────────

  openAddDialog(): void {
    this.editingMember    = null;
    this.showMemberDialog = true;
  }

  openEditDialog(member: MemberListItemDto): void {
    this.memberApi.getById(member.id).subscribe(dto => {
      this.editingMember    = dto;
      this.showMemberDialog = true;
    });
  }

  closeMemberDialog(): void {
    this.showMemberDialog = false;
    this.editingMember    = null;
  }

  onMemberSaved(request: CreateMemberRequest): void {
    if (this.editingMember) {
      this.memberApi.update(this.editingMember.id, request).subscribe(() => {
        this.closeMemberDialog();
        this.loadData();
      });
    } else {
      this.memberApi.create(request).subscribe(() => {
        this.closeMemberDialog();
        this.loadData();
      });
    }
  }

  deleteMember(member: MemberListItemDto): void {
    if (!confirm(`Delete ${memberDisplayName(member)}? This cannot be undone.`)) return;
    this.memberApi.delete(member.id).subscribe(() => this.loadData());
  }

  // ── Create User Account ─────────────────────────────────────────────────────

  openCreateUserDialog(member: MemberListItemDto): void {
    this.selectedMemberForUser = member;
    this.showCreateUserDialog  = true;
  }

  closeCreateUserDialog(): void {
    this.showCreateUserDialog  = false;
    this.selectedMemberForUser = null;
  }

  onUserCreated(): void {
    this.closeCreateUserDialog();
    this.loadData();
  }

  // ── Invitation Link ─────────────────────────────────────────────────────────

  openInviteDialog(member: MemberListItemDto): void {
    this.selectedMemberForInvite = member;
    this.showInviteDialog        = true;
  }

  closeInviteDialog(): void {
    this.showInviteDialog        = false;
    this.selectedMemberForInvite = null;
    // An invitation may have just created an account, so refresh the grid.
    this.loadData();
  }

  // ── Send Push (one-to-one test) ──────────────────────────────────────────────

  openPushDialog(member: MemberListItemDto): void {
    this.selectedMemberForPush = member;
    this.showPushDialog        = true;
  }

  closePushDialog(): void {
    this.showPushDialog        = false;
    this.selectedMemberForPush = null;
  }
}
