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

type TGatewayDnsRecord = appstate.INetworkState['gatewayDnsRecords'][number];

@customElement('ob-view-dns-records')
export class ObViewDnsRecords extends DeesElement {
  @state()
  accessor networkState: appstate.INetworkState = {
    targets: [],
    stats: null,
    statsResource: { phase: 'idle', error: null, lastSuccessAt: 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`
      .name { font-weight: 600; }
      .value { font-family: monospace; color: var(--ci-shade-5, #71717a); overflow-wrap: anywhere; }
      .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; }
      .missing { color: #dc2626; }
      .empty { padding: 32px; text-align: center; color: var(--ci-shade-5, #71717a); }
    `,
  ];

  async connectedCallback() {
    super.connectedCallback();
    await appstate.dispatchProtectedAction(appstate.fetchGatewayDnsRecordsAction, null);
  }

  public render(): TemplateResult {
    const records = this.networkState.gatewayDnsRecords;
    return html`
      <ob-sectionheading>DNS Records</ob-sectionheading>
      ${records.length
        ? html`
            <dees-table
              .heading1=${'Gateway DNS Records'}
              .heading2=${'DNS records published through dcrouter for Onebox services'}
              .data=${records}
              .showColumnFilters=${true}
              .displayFunction=${(record: TGatewayDnsRecord) => ({
                Name: html`
                  <div>
                    <div class="name">${record.name}</div>
                    ${record.domainName ? html`<div class="muted">${record.domainName}</div>` : ''}
                  </div>
                `,
                Type: html`<span class="badge">${record.type}</span>`,
                Value: html`<span class="value">${record.value || '-'}</span>`,
                Status: html`<span class=${record.status === 'missing' ? 'missing' : ''}>${record.status}</span>`,
                Service: record.serviceName || record.appId || '-',
              })}
              .dataActions=${[
                {
                  name: 'Refresh',
                  iconName: 'lucide:rotateCw',
                  type: ['header'],
                  actionFunc: async () => {
                    await appstate.dispatchProtectedAction(
      appstate.fetchGatewayDnsRecordsAction,
                      null,
                    );
                  },
                },
                {
                  name: 'View service',
                  iconName: 'lucide:boxes',
                  type: ['inRow', 'contextmenu'],
                  actionFunc: async () => {
                    appRouter.navigateToView('services');
                  },
                },
                {
                  name: 'Manage in dcrouter',
                  iconName: 'lucide:externalLink',
                  type: ['inRow', 'contextmenu'],
                  actionRelevancyCheckFunc: (record: TGatewayDnsRecord) => !!record.manageUrl,
                  actionFunc: async (actionData: plugins.deesCatalog.ITableActionDataArg<TGatewayDnsRecord>) => {
                    if (actionData.item.manageUrl) {
                      globalThis.open(actionData.item.manageUrl, '_blank', 'noopener');
                    }
                  },
                },
              ] as plugins.deesCatalog.ITableAction<TGatewayDnsRecord>[]}
            ></dees-table>
          `
        : html`<div class="empty">No gateway DNS records found. Configure a dcrouter gateway in Settings.</div>`}
    `;
  }
}
