import * as plugins from '../plugins.js';
import * as shared from './shared/index.js';
import * as appstate from '../appstate.js';
import {
  DeesElement,
  customElement,
  html,
  state,
  css,
  cssManager,
  type TemplateResult,
} from '@design.estate/dees-element';

@customElement('ob-view-settings')
export class ObViewSettings extends DeesElement {
  @state()
  accessor settingsState: appstate.ISettingsState = {
    settings: null,
    backupPasswordConfigured: false,
  };

  @state()
  accessor loginState: appstate.ILoginState = {
    identity: null,
    isLoggedIn: false,
  };

  constructor() {
    super();

    const settingsSub = appstate.settingsStatePart
      .select((s) => s)
      .subscribe((newState) => {
        this.settingsState = newState;
      });
    this.rxSubscriptions.push(settingsSub);

    const loginSub = appstate.loginStatePart
      .select((s) => s)
      .subscribe((newState) => {
        this.loginState = newState;
      });
    this.rxSubscriptions.push(loginSub);
  }

  public static styles = [
    cssManager.defaultStyles,
    shared.viewHostCss,
    css``,
  ];

  async connectedCallback() {
    super.connectedCallback();
    await appstate.settingsStatePart.dispatchAction(appstate.fetchSettingsAction, null);
  }

  public render(): TemplateResult {
    return html`
      <ob-sectionheading>Settings</ob-sectionheading>
      <sz-settings-view
        .settings=${this.settingsState.settings || {
          darkMode: true,
          cloudflareToken: '',
          cloudflareZoneId: '',
          autoRenewCerts: false,
          renewalThreshold: 30,
          acmeEmail: '',
          httpPort: 80,
          httpsPort: 443,
          forceHttps: false,
        }}
        .currentUser=${this.loginState.identity?.username || 'admin'}
        @setting-change=${(e: CustomEvent) => {
          const { key, value } = e.detail;
          appstate.settingsStatePart.dispatchAction(appstate.updateSettingsAction, {
            settings: { [key]: value },
          });
        }}
        @save=${(e: CustomEvent) => {
          appstate.settingsStatePart.dispatchAction(appstate.updateSettingsAction, {
            settings: e.detail,
          });
        }}
        @change-password=${(e: CustomEvent) => {
          console.log('Change password requested:', e.detail);
        }}
        @reset=${() => {
          appstate.settingsStatePart.dispatchAction(appstate.fetchSettingsAction, null);
        }}
      ></sz-settings-view>
    `;
  }
}
