'use client';

import { useEffect, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  createLogDrain,
  deleteLogDrain,
  getLogDrainSecret,
  listLogDrains,
  testLogDrain,
  updateLogDrain,
  type LogDrain,
  type LogDrainDestination,
  type LogDrainFilter,
} from '@/features/developer/api.client';
import { errorText } from '@/lib/api/errors';
import { when } from '../legacy-apps/data';
import { LaModal, useConfirm } from '../legacy-apps/ui';
import { SuBadge, useCopy } from '../settings-ui';
import { DevHead } from './shared';
import './development.css';

/**
 * Development › Monitoring › Log Drains (HUB-745, QA #731; design settings-log-drains.php): send
 * the account's API call log on to a log tool as it grows. Destinations: any https address
 * (signed JSON batches), Datadog or Honeycomb (their HTTP intake), Sentry (its envelope intake) or
 * a syslog server over TLS (RFC 5424; QA #936). All calls, or errors only.
 */

const DESTINATIONS: Record<
  LogDrainDestination,
  { label: string; tagline: string; url: string; keyLabel: string; keyHelp: string }
> = {
  datadog: {
    label: 'Datadog',
    tagline: 'Log management, dashboards and monitors.',
    url: 'https://http-intake.logs.datadoghq.com/api/v2/logs',
    keyLabel: 'Datadog API key',
    keyHelp: 'Sent as DD-API-KEY. Use your site’s intake URL (e.g. datadoghq.eu) if not US1.',
  },
  honeycomb: {
    label: 'Honeycomb',
    tagline: 'Deep tracing and observability.',
    url: 'https://api.honeycomb.io/1/batch/crm-api',
    keyLabel: 'Honeycomb ingest key',
    keyHelp: 'Sent as X-Honeycomb-Team. The URL ends with your dataset name.',
  },
  sentry: {
    label: 'Sentry',
    tagline: 'Error tracking and alerting.',
    url: 'https://o0.ingest.sentry.io/api/0/envelope/',
    keyLabel: 'Sentry public key',
    keyHelp:
      'The key of your project DSN (https://<key>@oN.ingest.sentry.io/<project>). Use your DSN’s host and project in the URL.',
  },
  syslog: {
    label: 'Syslog over TLS',
    tagline: 'Any RFC 5424 syslog server (Papertrail, rsyslog, Logtail…).',
    url: 'syslog+tls://logs.example.com:6514',
    keyLabel: 'Token (optional)',
    keyHelp: 'Put in front of each line, for services that ask for one.',
  },
  https: {
    label: 'HTTPS endpoint',
    tagline: 'Any https address: signed JSON batches, like webhooks.',
    url: '',
    keyLabel: 'Authorization header (optional)',
    keyHelp: 'Sent as the Authorization header, e.g. "Bearer abc123".',
  },
};

const STATUS: Record<
  LogDrain['status'],
  { label: string; tone: 'success' | 'warning' | 'danger' }
> = {
  active: { label: 'Healthy', tone: 'success' },
  paused: { label: 'Paused', tone: 'warning' },
  failing: { label: 'Failing', tone: 'danger' },
};

interface Form {
  name: string;
  destination: LogDrainDestination;
  endpointUrl: string;
  apiKey: string;
  filter: LogDrainFilter;
}
const emptyForm = (destination: LogDrainDestination): Form => ({
  name: DESTINATIONS[destination].label,
  destination,
  endpointUrl: DESTINATIONS[destination].url,
  apiKey: '',
  filter: 'all',
});

export function LogDrainsView() {
  const toast = useToast();
  const copy = useCopy();
  const [ask, confirmElement] = useConfirm();
  const [drains, setDrains] = useState<LogDrain[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [form, setForm] = useState<Form | null>(null);
  const [formError, setFormError] = useState<string | null>(null);
  const [busy, setBusy] = useState<string | null>(null);

  useEffect(() => {
    listLogDrains().then(setDrains, (err: unknown) => setError(errorText(err)));
  }, []);

  const replace = (d: LogDrain) =>
    setDrains((cur) => (cur ?? []).map((x) => (x.id === d.id ? d : x)));

  const save = async () => {
    if (!form) return;
    setFormError(null);
    setBusy('form');
    try {
      const created = await createLogDrain({
        name: form.name.trim(),
        destination: form.destination,
        endpointUrl: form.endpointUrl.trim(),
        filter: form.filter,
        ...(form.apiKey.trim() ? { apiKey: form.apiKey.trim() } : {}),
      });
      setDrains((cur) => [...(cur ?? []), created]);
      setForm(null);
      const test = await testLogDrain(created.id).catch(() => null);
      toast(
        test?.ok
          ? `${created.name} added and reached its endpoint`
          : `${created.name} added, but the test send failed: ${test?.error ?? 'no answer'}`,
        test?.ok ? 'success' : 'danger',
      );
    } catch (err) {
      setFormError(errorText(err));
    } finally {
      setBusy(null);
    }
  };

  const act = async (drain: LogDrain, work: () => Promise<void>) => {
    setBusy(drain.id);
    try {
      await work();
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(null);
    }
  };

  const test = (drain: LogDrain) =>
    act(drain, async () => {
      const res = await testLogDrain(drain.id);
      toast(
        res.ok
          ? `Test entry delivered (${res.httpStatus}, ${res.responseMs} ms)`
          : `Test failed: ${res.error ?? 'no answer'}`,
        res.ok ? 'success' : 'danger',
      );
    });

  const pauseOrResume = (drain: LogDrain) =>
    act(drain, async () => {
      replace(
        await updateLogDrain(drain.id, { status: drain.status === 'active' ? 'paused' : 'active' }),
      );
    });

  const remove = async (drain: LogDrain) => {
    const choice = await ask(
      `Delete ${drain.name}?`,
      <p>Calls stop going to {drain.endpointUrl}. This can&apos;t be undone.</p>,
      [{ label: 'Cancel' }, { label: 'Delete drain', primary: true }],
    );
    if (choice !== 1) return;
    await act(drain, async () => {
      await deleteLogDrain(drain.id);
      setDrains((cur) => (cur ?? []).filter((d) => d.id !== drain.id));
    });
  };

  const copySecret = (drain: LogDrain) =>
    act(drain, async () => {
      await copy(await getLogDrainSecret(drain.id));
    });

  const meta = form ? DESTINATIONS[form.destination] : null;

  return (
    <div className="dv-page">
      <DevHead
        title="Log Drains"
        intro="Send this account's API call log to your own log tools as it happens, to keep it longer than 30 days and alert on errors."
        actions={
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            onClick={() => setForm(emptyForm('https'))}
          >
            Add log drain
          </button>
        }
      />

      <section className="sk-detail-card dv-hero">
        <h2>Offload your logs with a log drain</h2>
        <ul>
          <li>Every API call of your apps and keys, or only the failed ones.</li>
          <li>
            Sent in batches every few seconds, signed so you can check they came from the CRM.
          </li>
          <li>Paused automatically after repeated failed sends, so nothing piles up.</li>
        </ul>
      </section>

      <div className="dv-cards">
        {(['datadog', 'honeycomb', 'sentry'] as const).map((d) => (
          <section key={d} className="sk-detail-card dv-partner">
            <h2>{DESTINATIONS[d].label}</h2>
            <p className="sk-muted">{DESTINATIONS[d].tagline}</p>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setForm(emptyForm(d))}
            >
              Get started
            </button>
          </section>
        ))}
      </div>

      <section className="sk-table-card">
        {error ? (
          <div className="sk-empty">
            <p>{error}</p>
          </div>
        ) : drains === null ? (
          <div className="sk-empty">
            <p>Loading…</p>
          </div>
        ) : !drains.length ? (
          <div className="sk-empty">
            <strong>No log drains yet</strong>
            <p>Add one to start sending your API call log.</p>
          </div>
        ) : (
          <div className="sk-table-wrap">
            <table className="sk-table">
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Destination</th>
                  <th>Filter</th>
                  <th>Status</th>
                  <th>Delivered</th>
                  <th className="sk-actions-col">Actions</th>
                </tr>
              </thead>
              <tbody>
                {drains.map((d) => (
                  <tr key={d.id}>
                    <td>
                      <strong>{d.name}</strong>
                      <span className="dv-sub su-mono">{d.endpointUrl}</span>
                    </td>
                    <td>{DESTINATIONS[d.destination].label}</td>
                    <td>{d.filter === 'all' ? 'All calls' : 'Errors only'}</td>
                    <td>
                      <SuBadge tone={STATUS[d.status].tone}>{STATUS[d.status].label}</SuBadge>
                      {d.lastError ? <span className="dv-sub">{d.lastError}</span> : null}
                    </td>
                    <td>
                      {d.deliveredCount.toLocaleString()}
                      <span className="dv-sub">Last: {when(d.lastDeliveredAt)}</span>
                    </td>
                    <td className="sk-actions-col">
                      <div className="dv-row-actions">
                        <button
                          type="button"
                          className="sk-text-btn"
                          disabled={busy === d.id}
                          onClick={() => void test(d)}
                        >
                          Send test
                        </button>
                        <button
                          type="button"
                          className="sk-text-btn"
                          disabled={busy === d.id}
                          onClick={() => void pauseOrResume(d)}
                        >
                          {d.status === 'active' ? 'Pause' : 'Resume'}
                        </button>
                        {d.destination === 'https' ? (
                          <button
                            type="button"
                            className="sk-text-btn"
                            disabled={busy === d.id}
                            onClick={() => void copySecret(d)}
                          >
                            Copy signing secret
                          </button>
                        ) : null}
                        <button
                          type="button"
                          className="sk-text-btn"
                          disabled={busy === d.id}
                          onClick={() => void remove(d)}
                        >
                          Delete
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>

      <LaModal open={form !== null} title="Add log drain" onClose={() => setForm(null)}>
        {form && meta ? (
          <form
            onSubmit={(e) => {
              e.preventDefault();
              void save();
            }}
          >
            <div className="la-modal-body dv-form">
              <label>
                <span>Destination</span>
                <select
                  className="input"
                  value={form.destination}
                  onChange={(e) => {
                    const destination = e.target.value as LogDrainDestination;
                    setForm({
                      ...emptyForm(destination),
                      name:
                        form.name === DESTINATIONS[form.destination].label
                          ? DESTINATIONS[destination].label
                          : form.name,
                    });
                  }}
                >
                  {(Object.keys(DESTINATIONS) as LogDrainDestination[]).map((d) => (
                    <option key={d} value={d}>
                      {DESTINATIONS[d].label}
                    </option>
                  ))}
                </select>
              </label>
              <label>
                <span>Name</span>
                <input
                  className="input"
                  required
                  maxLength={100}
                  value={form.name}
                  onChange={(e) => setForm({ ...form, name: e.target.value })}
                />
              </label>
              <label>
                <span>Endpoint URL</span>
                <input
                  className="input"
                  type="url"
                  required
                  placeholder="https://"
                  value={form.endpointUrl}
                  onChange={(e) => setForm({ ...form, endpointUrl: e.target.value })}
                />
              </label>
              <label>
                <span>{meta.keyLabel}</span>
                <input
                  className="input"
                  type="password"
                  autoComplete="off"
                  required={['datadog', 'honeycomb', 'sentry'].includes(form.destination)}
                  value={form.apiKey}
                  onChange={(e) => setForm({ ...form, apiKey: e.target.value })}
                />
                <small className="sk-help">{meta.keyHelp}</small>
              </label>
              <fieldset>
                <legend>Send</legend>
                <label className="dv-radio">
                  <input
                    type="radio"
                    name="dv-filter"
                    checked={form.filter === 'all'}
                    onChange={() => setForm({ ...form, filter: 'all' })}
                  />
                  All API calls
                </label>
                <label className="dv-radio">
                  <input
                    type="radio"
                    name="dv-filter"
                    checked={form.filter === 'errors'}
                    onChange={() => setForm({ ...form, filter: 'errors' })}
                  />
                  Errors only (4xx and 5xx)
                </label>
              </fieldset>
              {formError ? <p className="dv-error">{formError}</p> : null}
            </div>
            <footer className="la-modal-foot">
              <button
                type="button"
                className="btn-crm btn-crm--outline"
                onClick={() => setForm(null)}
              >
                Cancel
              </button>
              <button type="submit" className="btn-crm btn-crm--primary" disabled={busy === 'form'}>
                {busy === 'form' ? 'Adding…' : 'Add and test'}
              </button>
            </footer>
          </form>
        ) : null}
      </LaModal>
      {confirmElement}
    </div>
  );
}
