'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import {
  getServiceKeyUsage,
  listServiceKeyRequests,
  type ApiRequest,
  type ApiRequestQuery,
  type ApiUsage,
} from '@/features/integrations/api.client';
import { errorText } from '@/lib/api/errors';
import { CallDrawer, DateRange, endOfDay, startOfDay } from '../development/shared';
import { SuBadge } from '../settings-ui';
import { formatWhen, relative } from './data';

/**
 * A service key's API calls (GET /service-keys/:id/requests, newest first, 50 a page) and its
 * last-24-hours usage (GET /service-keys/:id/usage). Filters map to the API's `outcome` / `method`.
 */

const PAGE = 50;
const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] as const;

type Outcome = '' | NonNullable<ApiRequestQuery['outcome']>;
type Method = '' | NonNullable<ApiRequestQuery['method']>;

const statusTone = (code: number) =>
  code === 429 ? 'warning' : code >= 400 ? 'danger' : code >= 300 ? 'info' : 'success';

export function ServiceKeyLogs({ keyId }: { keyId: string }) {
  const [usage, setUsage] = useState<ApiUsage | null>(null);
  const [usageError, setUsageError] = useState<string | null>(null);
  const [rows, setRows] = useState<ApiRequest[] | null>(null);
  const [cursor, setCursor] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loadingMore, setLoadingMore] = useState(false);
  const [outcome, setOutcome] = useState<Outcome>('');
  const [method, setMethod] = useState<Method>('');
  // HUB-745 (QA #734): a date range, and a call's details in the drawer.
  const [range, setRange] = useState({ from: '', to: '' });
  const [open, setOpen] = useState<string | null>(null);
  const closeDrawer = useCallback(() => setOpen(null), []);
  /** Answers to an older filter / key are dropped. */
  const run = useRef(0);

  const query = useCallback(
    (next?: string): ApiRequestQuery => ({
      limit: PAGE,
      ...(next ? { cursor: next } : {}),
      ...(outcome ? { outcome } : {}),
      ...(method ? { method } : {}),
      ...(range.from ? { from: startOfDay(range.from) } : {}),
      ...(range.to ? { to: endOfDay(range.to) } : {}),
    }),
    [outcome, method, range],
  );

  const load = useCallback(() => {
    const id = ++run.current;
    setRows(null);
    setError(null);
    setCursor(null);
    listServiceKeyRequests(keyId, query()).then(
      (res) => {
        if (id !== run.current) return;
        setRows(res.data);
        setCursor(res.nextCursor ?? null);
      },
      (err: unknown) => id === run.current && setError(errorText(err)),
    );
    setUsageError(null);
    getServiceKeyUsage(keyId).then(
      (u) => id === run.current && setUsage(u),
      (err: unknown) => id === run.current && setUsageError(errorText(err)),
    );
  }, [keyId, query]);

  useEffect(load, [load]);

  const loadMore = () => {
    if (!cursor) return;
    const id = run.current;
    setLoadingMore(true);
    listServiceKeyRequests(keyId, query(cursor))
      .then(
        (res) => {
          if (id !== run.current) return;
          setRows((cur) => [...(cur ?? []), ...res.data]);
          setCursor(res.nextCursor ?? null);
        },
        (err: unknown) => id === run.current && setError(errorText(err)),
      )
      .finally(() => setLoadingMore(false));
  };

  const filtered = Boolean(outcome || method || range.from || range.to);
  const stat = (label: string, value: string) => (
    <div className="card su-stat">
      <div className="su-stat__label">{label}</div>
      <div className="su-stat__value">{value}</div>
    </div>
  );

  return (
    <>
      <section className="sk-detail-card" aria-label="Usage in the last 24 hours">
        <div className="sk-detail-card-heading">
          <h2>Usage</h2>
          <span className="sk-count">
            Last 24 hours
            {usage ? ` · last call ${relative(usage.lastCallAt) || 'never'}` : ''}
          </span>
        </div>
        {usageError ? (
          <p className="sk-muted">{usageError}</p>
        ) : (
          <div className="su-stats crm-mb-0">
            {stat('API calls', usage ? usage.calls24h.toLocaleString() : '…')}
            {stat('Errors', usage ? usage.errors24h.toLocaleString() : '…')}
            {stat('Rate-limited', usage ? usage.rateLimited24h.toLocaleString() : '…')}
          </div>
        )}
      </section>

      <section className="sk-detail-card" aria-label="API call logs">
        <div className="sk-detail-card-heading">
          <h2>API call logs</h2>
          <button type="button" className="btn-crm btn-crm--outline" onClick={load}>
            Refresh
          </button>
        </div>
        <div className="su-toolbar">
          <label className="crm-visually-hidden" htmlFor="sk-log-outcome">
            Outcome
          </label>
          <select
            id="sk-log-outcome"
            className="input"
            value={outcome}
            onChange={(e) => setOutcome(e.target.value as Outcome)}
          >
            <option value="">All responses</option>
            <option value="success">Successful (below 400)</option>
            <option value="error">Errors (400 and up)</option>
          </select>
          <label className="crm-visually-hidden" htmlFor="sk-log-method">
            Method
          </label>
          <select
            id="sk-log-method"
            className="input"
            value={method}
            onChange={(e) => setMethod(e.target.value as Method)}
          >
            <option value="">All methods</option>
            {METHODS.map((m) => (
              <option key={m} value={m}>
                {m}
              </option>
            ))}
          </select>
          <DateRange from={range.from} to={range.to} onChange={setRange} />
          {rows ? (
            <span className="su-toolbar__end su-count">
              {rows.length.toLocaleString()}
              {cursor ? '+' : ''} {rows.length === 1 ? 'call' : 'calls'}
            </span>
          ) : null}
        </div>
        <div className="sk-table-wrap">
          <table className="sk-table">
            <thead>
              <tr>
                <th scope="col">Time</th>
                <th scope="col">Method</th>
                <th scope="col">Route</th>
                <th scope="col">Status</th>
                <th scope="col">Duration</th>
                <th scope="col">IP address</th>
              </tr>
            </thead>
            <tbody>
              {(rows ?? []).map((r) => (
                <tr
                  key={r.id}
                  className="dv-click-row"
                  tabIndex={0}
                  title="Open the call's details"
                  onClick={() => setOpen(r.id)}
                  onKeyDown={(e) => (e.key === 'Enter' || e.key === ' ') && setOpen(r.id)}
                >
                  <td className="crm-text-nowrap" title={relative(r.createdAt)}>
                    {formatWhen(r.createdAt)}
                  </td>
                  <td>
                    <span className="su-mono">{r.method}</span>
                  </td>
                  <td>
                    <span className="su-mono">{r.route}</span>
                  </td>
                  <td>
                    <SuBadge tone={statusTone(r.statusCode)}>{r.statusCode}</SuBadge>
                  </td>
                  <td>{r.durationMs.toLocaleString()} ms</td>
                  <td>
                    <span className="su-mono">{r.ip ?? '—'}</span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {rows === null || rows.length === 0 || error ? (
          <div className="sk-empty">
            {error ? (
              <>
                <strong>Couldn&apos;t load the logs</strong>
                <p>{error}</p>
                <button type="button" className="btn-crm btn-crm--outline" onClick={load}>
                  Try again
                </button>
              </>
            ) : rows === null ? (
              <p>Loading API calls…</p>
            ) : (
              <>
                <strong>{filtered ? 'No calls match these filters' : 'No API calls yet'}</strong>
                <p>
                  {filtered
                    ? 'Try another outcome, method or dates.'
                    : 'Calls made with this key appear here, newest first.'}
                </p>
              </>
            )}
          </div>
        ) : null}
        {cursor && !error ? (
          <div className="crm-text-center crm-mt-3">
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              disabled={loadingMore}
              onClick={loadMore}
            >
              {loadingMore ? 'Loading…' : 'Load more'}
            </button>
          </div>
        ) : null}
      </section>
      <CallDrawer id={open} onClose={closeDrawer} />
    </>
  );
}
