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

declare global {
  interface HTMLElementTagNameMap {
    'ops-view-emails': OpsViewEmails;
  }
}

@customElement('ops-view-emails')
export class OpsViewEmails extends DeesElement {
  @state()
  accessor emails: interfaces.requests.IEmail[] = [];

  @state()
  accessor selectedEmail: interfaces.requests.IEmailDetail | null = null;

  @state()
  accessor currentView: 'list' | 'detail' = 'list';

  @state()
  accessor isLoading = false;

  private stateSubscription: any;

  async connectedCallback() {
    await super.connectedCallback();
    this.stateSubscription = appstate.emailOpsStatePart.select().subscribe((state) => {
      this.emails = state.emails;
      this.isLoading = state.isLoading;
    });
    // Initial fetch
    await appstate.emailOpsStatePart.dispatchAction(appstate.fetchAllEmailsAction, null);
  }

  async disconnectedCallback() {
    await super.disconnectedCallback();
    if (this.stateSubscription) {
      this.stateSubscription.unsubscribe();
    }
  }

  public static styles = [
    cssManager.defaultStyles,
    shared.viewHostCss,
    css`
      :host {
        display: block;
        height: 100%;
      }

      .viewContainer {
        height: 100%;
      }
    `,
  ];

  public render() {
    return html`
      <dees-heading level="3">Email Log</dees-heading>
      <div class="viewContainer">
        ${this.currentView === 'detail' && this.selectedEmail
          ? html`
              <sz-mta-detail-view
                .email=${this.selectedEmail}
                @back=${this.handleBack}
              ></sz-mta-detail-view>
            `
          : html`
              <sz-mta-list-view
                .emails=${this.emails}
                @email-click=${this.handleEmailClick}
              ></sz-mta-list-view>
            `
        }
      </div>
    `;
  }

  private async handleEmailClick(e: CustomEvent<interfaces.requests.IEmail>) {
    const emailSummary = e.detail;
    try {
      const context = appstate.loginStatePart.getState()!;
      const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
        interfaces.requests.IReq_GetEmailDetail
      >('/typedrequest', 'getEmailDetail');

      const response = await request.fire({
        identity: context.identity!,
        emailId: emailSummary.id,
      });

      if (response.email) {
        this.selectedEmail = response.email;
        this.currentView = 'detail';
      }
    } catch (error) {
      console.error('Failed to fetch email detail:', error);
    }
  }

  private handleBack() {
    this.selectedEmail = null;
    this.currentView = 'list';
  }
}
