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

@customElement('gitops-view-projects')
export class GitopsViewProjects extends DeesElement {
  @state()
  accessor connectionsState: appstate.IConnectionsState = {
    connections: [],
    activeConnectionId: null,
  };

  @state()
  accessor dataState: appstate.IDataState = {
    projects: [],
    groups: [],
    secrets: [],
    pipelines: [],
    pipelineJobs: [],
    currentJobLog: '',
  };

  @state()
  accessor selectedConnectionId: string = '';

  private _autoRefreshHandler: () => void;

  constructor() {
    super();
    const connSub = appstate.connectionsStatePart
      .select((s) => s)
      .subscribe((s) => { this.connectionsState = s; });
    this.rxSubscriptions.push(connSub);

    const dataSub = appstate.dataStatePart
      .select((s) => s)
      .subscribe((s) => { this.dataState = s; });
    this.rxSubscriptions.push(dataSub);

    this._autoRefreshHandler = () => this.handleAutoRefresh();
    document.addEventListener('gitops-auto-refresh', this._autoRefreshHandler);
  }

  public override disconnectedCallback() {
    super.disconnectedCallback();
    document.removeEventListener('gitops-auto-refresh', this._autoRefreshHandler);
  }

  private handleAutoRefresh(): void {
    this.loadProjects();
  }

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

  public render(): TemplateResult {
    const connectionOptions = this.connectionsState.connections.map((c) => ({
      option: `${c.name} (${c.providerType})`,
      key: c.id,
    }));

    return html`
      <div class="view-title">Projects</div>
      <div class="view-description">Browse projects from your connected providers</div>
      <div class="toolbar">
        <dees-input-dropdown
          .label=${'Connection'}
          .options=${connectionOptions}
          .selectedOption=${connectionOptions.find((o) => o.key === this.selectedConnectionId) || connectionOptions[0]}
          @selectedOption=${(e: CustomEvent) => {
            this.selectedConnectionId = e.detail.key;
            this.loadProjects();
          }}
        ></dees-input-dropdown>
        <dees-button @click=${() => this.loadProjects()}>Refresh</dees-button>
      </div>
      <dees-table
        .heading1=${'Projects'}
        .heading2=${'Repositories from the selected connection'}
        .data=${this.dataState.projects}
        .displayFunction=${(item: any) => ({
          Name: item.name,
          Path: item.fullPath,
          Visibility: item.visibility,
          Branch: item.defaultBranch,
          'Last Activity': item.lastActivity ? new Date(item.lastActivity).toLocaleDateString() : '-',
        })}
        .dataActions=${[
          {
            name: 'View Secrets',
            iconName: 'lucide:key',
            type: ['inRow', 'contextmenu'],
            actionFunc: async ({ item }: any) => {
              appstate.uiStatePart.dispatchAction(appstate.setActiveViewAction, {
                view: 'secrets',
                navigationContext: {
                  connectionId: this.selectedConnectionId,
                  scope: 'project',
                  scopeId: item.id,
                },
              });
            },
          },
          {
            name: 'View Pipelines',
            iconName: 'lucide:play',
            type: ['inRow', 'contextmenu'],
            actionFunc: async ({ item }: any) => {
              appstate.uiStatePart.dispatchAction(appstate.setActiveViewAction, {
                view: 'pipelines',
                navigationContext: {
                  connectionId: this.selectedConnectionId,
                  projectId: item.id,
                },
              });
            },
          },
        ]}
      ></dees-table>
    `;
  }

  async firstUpdated() {
    await appstate.connectionsStatePart.dispatchAction(appstate.fetchConnectionsAction, null);
    const conns = appstate.connectionsStatePart.getState().connections;
    if (conns.length > 0 && !this.selectedConnectionId) {
      this.selectedConnectionId = conns[0].id;
      await this.loadProjects();
    }
  }

  private async loadProjects() {
    if (!this.selectedConnectionId) return;
    await appstate.dataStatePart.dispatchAction(appstate.fetchProjectsAction, {
      connectionId: this.selectedConnectionId,
    });
  }
}
