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 { LayoutModule } from '@progress/kendo-angular-layout';
import { DropDownsModule } from '@progress/kendo-angular-dropdowns';
import { DisbursementApiService } from '../../services/disbursement-api.service';
import { ChurchProfileDto, UpdateChurchProfileRequest } from '../../models/disbursement.model';
import { HasPermissionDirective } from '../../../../core/directives/has-permission.directive';
import { PermissionModules } from '../../../../core/models/permission.model';
import { SiteSettingsTabComponent } from '../../../settings/components/site-settings-tab/site-settings-tab.component';
import { NotificationSettingsTabComponent } from '../../../settings/components/notification-settings-tab/notification-settings-tab.component';

@Component({
  selector: 'app-church-profile-page',
  standalone: true,
  imports: [
    CommonModule, FormsModule, ButtonsModule, InputsModule, LayoutModule, DropDownsModule,
    HasPermissionDirective, SiteSettingsTabComponent, NotificationSettingsTabComponent,
  ],
  templateUrl: './church-profile-page.component.html',
})
export class ChurchProfilePageComponent implements OnInit {
  model: ChurchProfileDto | null = null;
  saving = false;
  savedMsg = '';

  /** Bound to the password inputs; blank means "keep the saved key". Reset after each save. */
  claudeApiKeyInput = '';
  geminiApiKeyInput = '';

  readonly aiProviders = [
    { text: 'Claude', value: 'Claude' },
    { text: 'Gemini', value: 'Gemini' },
  ];

  /** Settings module gates the Site / Notification tabs. */
  readonly settingsPermission = { module: PermissionModules.Settings, action: 'read' as const };

  constructor(private api: DisbursementApiService) {}

  ngOnInit(): void {
    this.api.getChurchProfile().subscribe(p => (this.model = p));
  }

  save(): void {
    if (!this.model || this.saving) return;
    this.saving = true;
    this.savedMsg = '';
    const { id, claudeApiKeyMasked, geminiApiKeyMasked, ...rest } = this.model;
    const req: UpdateChurchProfileRequest = {
      ...rest,
      claudeApiKey: this.claudeApiKeyInput.trim() || null,
      geminiApiKey: this.geminiApiKeyInput.trim() || null,
    };
    this.api.updateChurchProfile(req).subscribe({
      next: () => {
        this.saving = false;
        this.savedMsg = 'Saved / 已儲存';
        // Clear the key inputs and reload so the masked placeholders reflect the new keys.
        this.claudeApiKeyInput = '';
        this.geminiApiKeyInput = '';
        this.api.getChurchProfile().subscribe(p => (this.model = p));
      },
      error: () => {
        // Error message is shown globally by httpErrorInterceptor.
        this.saving = false;
      },
    });
  }
}
