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

type TGatewayDomain = appstate.INetworkState['gatewayDomains'][number];

@customElement('ob-view-domains')
export class ObViewDomains extends DeesElement {
  @state()
  accessor networkState: appstate.INetworkState = {
    targets: [],
    stats: null,
    trafficStats: null,
    dnsRecords: [],
    domains: [],
    gatewayDomains: [],
    gatewayDnsRecords: [],
    certificates: [],
  };

  constructor() {
    super();
    const networkSub = appstate.networkStatePart.select((s) => s).subscribe((newState) => {
      this.networkState = newState;
    });
    this.rxSubscriptions.push(networkSub);
  }

  public static styles = [
    cssManager.defaultStyles,
    shared.viewHostCss,
    css`
      .domain { font-weight: 600; }
      .muted { color: var(--ci-shade-5, #71717a); font-size: 13px; }
      .badge { border-radius: 999px; padding: 3px 8px; background: var(--ci-shade-1, #f4f4f5); font-size: 12px; }
      .empty { padding: 32px; text-align: center; color: var(--ci-shade-5, #71717a); }
    `,
  ];

  async connectedCallback() {
    super.connectedCallback();
    await appstate.networkStatePart.dispatchAction(appstate.fetchGatewayDomainsAction, null);
  }

  public render(): TemplateResult {
    const domains = this.networkState.gatewayDomains;
    return html`
      <ob-sectionheading>Domains</ob-sectionheading>
      <div class="muted" style="margin-bottom: 16px;">
        Domains are managed in dcrouter. Onebox shows gateway visibility for deployed services.
      </div>
      ${domains.length
        ? html`
            <dees-table
              .heading1=${'Gateway Domains'}
              .heading2=${'Domains imported from dcrouter gateway visibility'}
              .data=${domains}
              .showColumnFilters=${true}
              .displayFunction=${(domain: TGatewayDomain) => ({
                Domain: html`
                  <div>
                    <div class="domain">${domain.name}</div>
                    ${domain.providerId ? html`<div class="muted">Provider: ${domain.providerId}</div>` : ''}
                  </div>
                `,
                Source: html`<span class="badge">${domain.source || 'dcrouter'}</span>`,
                Authoritative: domain.authoritative ? 'Yes' : 'No',
                Services: domain.serviceCount || 0,
              })}
              .dataActions=${[
                {
                  name: 'Refresh',
                  iconName: 'lucide:rotateCw',
                  type: ['header'],
                  actionFunc: async () => {
                    await appstate.networkStatePart.dispatchAction(
                      appstate.fetchGatewayDomainsAction,
                      null,
                    );
                  },
                },
                {
                  name: 'Manage in dcrouter',
                  iconName: 'lucide:externalLink',
                  type: ['inRow', 'contextmenu'],
                  actionRelevancyCheckFunc: (domain: TGatewayDomain) => !!domain.manageUrl,
                  actionFunc: async (actionData: plugins.deesCatalog.ITableActionDataArg<TGatewayDomain>) => {
                    if (actionData.item.manageUrl) {
                      globalThis.open(actionData.item.manageUrl, '_blank', 'noopener');
                    }
                  },
                },
              ] as plugins.deesCatalog.ITableAction<TGatewayDomain>[]}
            ></dees-table>
          `
        : html`<div class="empty">No gateway domains found. Configure a dcrouter gateway in Settings.</div>`}
    `;
  }
}
