'use client';

import { useState } from 'react';
import type { ServiceKey, Webhook } from '@/features/integrations/api.client';
import { DeliveriesLog } from '../legacy-apps/DeliveriesLog';
import { WebhookEditor } from '../legacy-apps/WebhookEditor';

/**
 * A service key's Webhooks tab: the key's webhook (target URL, throttling, subscriptions limited
 * to the objects its scopes can read) and, like Legacy Apps, the delivery log of real events with
 * View and Replay (#549).
 */
export function ServiceKeyWebhooks({ serviceKey }: { serviceKey: ServiceKey }) {
  const owner = { kind: 'service_key' as const, id: serviceKey.id };
  // undefined while the editor loads the webhook; null when there is none.
  const [hook, setHook] = useState<Webhook | null | undefined>(undefined);
  return (
    <>
      <section className="sk-detail-card">
        <WebhookEditor
          owner={owner}
          ownerLabel="key"
          scopes={serviceKey.effectiveScopes}
          onChange={setHook}
        />
      </section>
      <section className="sk-detail-card">
        <h2 className="ase-section-title">Delivery log</h2>
        <p className="ase-section-desc">
          Every event sent to this key&apos;s webhook in the last 30 days, with its attempts and the
          endpoint&apos;s answer. Replay sends the same event (same eventId) again.
        </p>
        <DeliveriesLog
          // A new webhook starts a new log: read it again.
          key={hook?.id ?? 'none'}
          owner={owner}
          hasWebhook={hook === undefined ? null : Boolean(hook)}
          emptyHint="Events sent to this webhook show up here. Use Send test above to check the endpoint."
          noWebhookHint="Set a target URL and event subscriptions above; its deliveries show up here."
        />
      </section>
    </>
  );
}
