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';
import { type IStatsTile } from '@design.estate/dees-catalog';

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

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

  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 {
    appstate.connectionsStatePart.dispatchAction(appstate.fetchConnectionsAction, null);
  }

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

  public render(): TemplateResult {
    const connCount = this.connectionsState.connections.length;
    const projCount = this.dataState.projects.length;
    const groupCount = this.dataState.groups.length;
    const pipelineCount = this.dataState.pipelines.length;
    const failedPipelines = this.dataState.pipelines.filter((p) => p.status === 'failed').length;

    const tiles: IStatsTile[] = [
      { id: 'connections', title: 'Connections', value: connCount, type: 'number', icon: 'lucide:plug', color: '#00acff' },
      { id: 'projects', title: 'Projects', value: projCount, type: 'number', icon: 'lucide:folderGit2', color: '#00acff' },
      { id: 'groups', title: 'Groups', value: groupCount, type: 'number', icon: 'lucide:users', color: '#00acff' },
      { id: 'pipelines', title: 'Pipelines', value: pipelineCount, type: 'number', icon: 'lucide:play', color: '#00acff' },
      { id: 'failed', title: 'Failed Pipelines', value: failedPipelines, type: 'number', icon: 'lucide:triangleAlert', color: failedPipelines > 0 ? '#ff4444' : '#00ff88' },
    ];

    return html`
      <div class="view-title">Overview</div>
      <div class="view-description">GitOps dashboard - manage your Gitea and GitLab instances</div>
      <dees-statsgrid .tiles=${tiles}></dees-statsgrid>
    `;
  }
}
