'use client';

import { useEffect, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  getWebhookDelivery,
  listWebhookDeliveries,
  replayWebhookDelivery,
  WEBHOOK_EVENT_LABELS,
  WEBHOOK_EVENT_TYPES,
  type WebhookDelivery,
  type WebhookDeliveryDetail,
  type WebhookEventType,
  type WebhookOwner,
} from '@/features/integrations/api.client';
import { errorText } from '@/lib/api/errors';
import { downloadCsv, when, WEBHOOK_OBJECT_CHOICES } from './data';
import {
  DatesSoon,
  ICON,
  LaModal,
  LogDropdown,
  NoLogs,
  PickOne,
  pickedLabel,
  S,
  useMenu,
} from './ui';

/** Logs › Webhooks: the deliveries of the app's (or key's) webhook, with detail and replay. */

type Status = WebhookDelivery['status'];
const STATUSES = [
  { value: 'success' as const, label: 'Success' },
  { value: 'failed' as const, label: 'Failed' },
  { value: 'pending' as const, label: 'Pending' },
];
const STATUS_TONE: Record<Status, string> = {
  success: 'badge--success',
  failed: 'badge--danger',
  pending: 'badge--warning',
};
const eventLabel = (t: string) => WEBHOOK_EVENT_LABELS[t as WebhookEventType] ?? t;
const PAGE = 100;

export function DeliveriesLog({
  owner,
  hasWebhook,
  emptyHint = "Events sent to this webhook show up here. Use Send test on the Edit app page's Webhooks tab.",
  noWebhookHint = 'Set a target URL and event subscriptions with Edit webhooks; its deliveries show up here.',
}: {
  owner: WebhookOwner;
  /** null while loading. */
  hasWebhook: boolean | null;
  /** Shown when the webhook has no deliveries yet (the service key page words it its own way). */
  emptyHint?: string;
  /** Shown when the owner has no webhook. */
  noWebhookHint?: string;
}) {
  const toast = useToast();
  const { menu, toggle, close } = useMenu();
  const [status, setStatus] = useState<Status | ''>('');
  const [eventType, setEventType] = useState<WebhookEventType | ''>('');
  const [objectType, setObjectType] = useState('');
  const [searchBy, setSearchBy] = useState<'event' | 'object'>('event');
  const [search, setSearch] = useState('');
  const [rows, setRows] = useState<WebhookDelivery[] | null>(null);
  const [cursor, setCursor] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loadingMore, setLoadingMore] = useState(false);
  const [reload, setReload] = useState(0);
  const [detail, setDetail] = useState<WebhookDeliveryDetail | null>(null);
  const [replaying, setReplaying] = useState(false);

  const { kind, id: ownerId } = owner;

  useEffect(() => {
    if (!hasWebhook) return;
    let live = true;
    setRows(null);
    setError(null);
    listWebhookDeliveries(
      { kind, id: ownerId },
      {
        limit: PAGE,
        status: status || undefined,
        eventType: eventType || undefined,
      },
    ).then(
      (res) => {
        if (!live) return;
        setRows(res.data);
        setCursor(res.nextCursor);
      },
      (err: unknown) => live && setError(errorText(err)),
    );
    return () => {
      live = false;
    };
  }, [hasWebhook, kind, ownerId, status, eventType, reload]);

  const loadMore = async () => {
    if (!hasWebhook || !cursor) return;
    setLoadingMore(true);
    try {
      const res = await listWebhookDeliveries(owner, {
        limit: PAGE,
        cursor,
        status: status || undefined,
        eventType: eventType || undefined,
      });
      setRows((cur) => [...(cur ?? []), ...res.data]);
      setCursor(res.nextCursor);
    } catch (err) {
      setError(errorText(err));
    } finally {
      setLoadingMore(false);
    }
  };

  const openDetail = async (id: string) => {
    try {
      setDetail(await getWebhookDelivery(id));
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const replay = async (id: string) => {
    setReplaying(true);
    try {
      await replayWebhookDelivery(id);
      toast('Delivery queued again', 'success');
      setDetail(null);
      setReload((n) => n + 1);
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setReplaying(false);
    }
  };

  if (hasWebhook === null) return <NoLogs title="Loading webhook…" text="One moment." />;
  if (!hasWebhook) {
    return <NoLogs title="No webhook set up yet." text={noWebhookHint} />;
  }

  const objectOptions = [
    ...new Set([...WEBHOOK_OBJECT_CHOICES, ...(rows ?? []).map((r) => r.objectType)]),
  ].map((o) => ({ value: o, label: o }));
  const q = search.trim().toLowerCase();
  const shown = (rows ?? []).filter(
    (r) =>
      (!objectType || r.objectType === objectType) &&
      (!q ||
        (searchBy === 'event' ? `${r.eventId} ${r.id}` : `${r.objectType} ${r.objectId ?? ''}`)
          .toLowerCase()
          .includes(q)),
  );

  return (
    <>
      <div className="la-log-filters">
        <span>Filter by:</span>
        <LogDropdown
          id="wh-object"
          label={pickedLabel('Object type', objectType)}
          open={menu}
          onToggle={toggle}
        >
          <PickOne options={objectOptions} value={objectType} onChange={setObjectType} />
        </LogDropdown>
        <LogDropdown
          id="wh-event"
          label={pickedLabel('Subscription type', eventType && eventLabel(eventType))}
          open={menu}
          onToggle={toggle}
          search
        >
          <PickOne
            options={WEBHOOK_EVENT_TYPES.map((t) => ({ value: t, label: eventLabel(t) }))}
            value={eventType}
            onChange={setEventType}
          />
        </LogDropdown>
        <LogDropdown
          id="wh-status"
          label={pickedLabel('Status', STATUSES.find((s) => s.value === status)?.label)}
          open={menu}
          onToggle={toggle}
        >
          <PickOne options={STATUSES} value={status} onChange={setStatus} />
        </LogDropdown>
        <DatesSoon />
      </div>
      <div className="la-log-search-row">
        <LogDropdown
          id="wh-search-by"
          label={searchBy === 'event' ? 'Event ID' : 'Object ID'}
          open={menu}
          onToggle={toggle}
        >
          <button
            type="button"
            onClick={() => {
              setSearchBy('event');
              close();
            }}
          >
            Event ID
          </button>
          <button
            type="button"
            onClick={() => {
              setSearchBy('object');
              close();
            }}
          >
            Object ID
          </button>
        </LogDropdown>
        <label className="la-log-search">
          <input
            type="search"
            placeholder={
              searchBy === 'event' ? 'Search loaded deliveries by event ID' : 'Search by object ID'
            }
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
          {ICON.search}
        </label>
        <button
          type="button"
          className="la-export"
          disabled={!shown.length}
          onClick={() =>
            downloadCsv('webhook-deliveries.csv', [
              [
                'Time',
                'Event',
                'Object type',
                'Object ID',
                'Status',
                'Attempts',
                'HTTP status',
                'Error',
                'Event ID',
              ],
              ...shown.map((r) => [
                r.createdAt,
                r.eventType,
                r.objectType,
                r.objectId,
                r.status,
                r.attempts,
                r.lastHttpStatus,
                r.lastError,
                r.eventId,
              ]),
            ])
          }
        >
          {ICON.download} Export logs (CSV)
        </button>
      </div>
      {error ? (
        <NoLogs title="Couldn't load deliveries." text={error} />
      ) : rows === null ? (
        <NoLogs title="Loading deliveries…" text="One moment." />
      ) : !shown.length ? (
        rows.length || status || eventType ? (
          <NoLogs />
        ) : (
          <NoLogs title="No deliveries yet." text={emptyHint} />
        )
      ) : (
        <div className="la-log-table-wrap">
          <table className="la-log-table">
            <thead>
              <tr>
                <th>Time</th>
                <th>Event</th>
                <th>Object</th>
                <th>Status</th>
                <th>Attempts</th>
                <th>Response</th>
                <th />
              </tr>
            </thead>
            <tbody>
              {shown.map((r) => (
                <tr key={r.id}>
                  <td>{when(r.createdAt)}</td>
                  <td style={S.keep}>
                    {eventLabel(r.eventType)}
                    {r.replayOf ? <small style={S.sub}>Replay</small> : null}
                  </td>
                  <td>
                    {r.objectType}
                    {r.objectId ? <small style={S.sub}>{r.objectId}</small> : null}
                  </td>
                  <td>
                    <span className={`badge ${STATUS_TONE[r.status]}`}>{r.status}</span>
                  </td>
                  <td>{r.attempts}</td>
                  <td>
                    {r.lastHttpStatus ?? '—'}
                    {r.lastError ? <small style={S.sub}>{r.lastError}</small> : null}
                  </td>
                  <td>
                    <div className="su-row-actions">
                      <button type="button" className="link" onClick={() => void openDetail(r.id)}>
                        View
                      </button>
                      <button
                        type="button"
                        className="link"
                        disabled={replaying}
                        onClick={() => void replay(r.id)}
                      >
                        Replay
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
      {rows && cursor ? (
        <div style={S.more}>
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            disabled={loadingMore}
            onClick={() => void loadMore()}
          >
            {loadingMore ? 'Loading…' : 'Load more'}
          </button>
        </div>
      ) : null}

      <LaModal open={detail !== null} title="Delivery" onClose={() => setDetail(null)}>
        {detail ? (
          <>
            <div className="la-modal-body">
              <p style={{ margin: '0 0 12px' }}>
                <span className={`badge ${STATUS_TONE[detail.status]}`}>{detail.status}</span>{' '}
                {eventLabel(detail.eventType)} · {detail.objectType}
                {detail.objectId ? ` ${detail.objectId}` : ''}
              </p>
              <p className="field__help" style={{ margin: 0 }}>
                Sent {when(detail.createdAt)} · {detail.attempts}{' '}
                {detail.attempts === 1 ? 'attempt' : 'attempts'}
                {detail.lastHttpStatus !== null ? ` · HTTP ${detail.lastHttpStatus}` : ''}
                {detail.lastResponseMs !== null ? ` · ${detail.lastResponseMs} ms` : ''}
                {detail.nextAttemptAt ? ` · next try ${when(detail.nextAttemptAt)}` : ''}
              </p>
              {detail.lastError ? (
                <p className="field__help" style={{ color: 'var(--danger)', margin: '8px 0 0' }}>
                  {detail.lastError}
                </p>
              ) : null}
              <p className="field__help" style={{ margin: '8px 0 0' }}>
                Event ID <span className="su-mono">{detail.eventId}</span>
              </p>
              <h3 style={{ margin: '18px 0 0', fontSize: 14 }}>Payload</h3>
              <pre style={S.pre}>{JSON.stringify(detail.payload, null, 2)}</pre>
              <h3 style={{ margin: '18px 0 0', fontSize: 14 }}>Response</h3>
              <pre style={S.pre}>{detail.lastResponseBody || '(empty)'}</pre>
            </div>
            <footer className="la-modal-foot">
              <button
                type="button"
                className="btn-crm btn-crm--outline"
                onClick={() => setDetail(null)}
              >
                Close
              </button>
              <button
                type="button"
                className="btn-crm btn-crm--primary"
                disabled={replaying}
                onClick={() => void replay(detail.id)}
              >
                Replay
              </button>
            </footer>
          </>
        ) : null}
      </LaModal>
    </>
  );
}
