'use client';

import { useEffect, useState, type ReactNode } from 'react';
import {
  getDeveloperLog,
  type ApiCredentialKind,
  type DeveloperLogDetail,
} from '@/features/developer/api.client';
import { errorText } from '@/lib/api/errors';
import { when } from '../legacy-apps/data';
import { ICON } from '../legacy-apps/ui';
import { useCopy } from '../settings-ui';
import './development.css';
import { endOfDay, startOfDay } from './dates';

export { endOfDay, startOfDay };

/** Pieces shared by the Development pages (HUB-745): dates, the call drawer, labels. */

export const KIND_LABEL: Record<ApiCredentialKind, string> = {
  private_app: 'Legacy app',
  service_key: 'Service key',
  developer_key: 'Developer API key',
  personal_key: 'Personal access key',
};

/** The design's from / to date pickers (QA #734): both optional, `to` included. */
export function DateRange({
  from,
  to,
  onChange,
}: {
  from: string;
  to: string;
  onChange: (range: { from: string; to: string }) => void;
}) {
  return (
    <div className="la-dates">
      <input
        type="date"
        aria-label="From date"
        value={from}
        max={to || undefined}
        onChange={(e) => onChange({ from: e.target.value, to })}
      />
      <span>to</span>
      <input
        type="date"
        aria-label="To date"
        value={to}
        min={from || undefined}
        onChange={(e) => onChange({ from, to: e.target.value })}
      />
      {from || to ? (
        <button
          type="button"
          className="sk-text-btn"
          onClick={() => onChange({ from: '', to: '' })}
        >
          Clear
        </button>
      ) : null}
    </div>
  );
}

export function StatusChip({ code }: { code: number }) {
  const tone = code < 300 ? 'success' : code === 429 ? 'warning' : code < 500 ? 'danger' : 'danger';
  return <span className={`badge badge--${tone}`}>{code}</span>;
}

function Block({ title, text }: { title: string; text: string | null }) {
  const copy = useCopy();
  return (
    <section className="dv-block">
      <header>
        <h3>{title}</h3>
        {text ? (
          <button type="button" className="sk-text-btn" onClick={() => void copy(text)}>
            Copy
          </button>
        ) : null}
      </header>
      <pre>{text ?? 'None'}</pre>
    </section>
  );
}

const headerText = (headers: Record<string, string>) =>
  Object.entries(headers)
    .map(([k, v]) => `${k}: ${v}`)
    .join('\n') || null;

/**
 * The slide-over with one call (the design's #drawerCallDetails): summary, and for a failed
 * call the request and answer saved for it (errors only; secrets masked).
 */
export function CallDrawer({ id, onClose }: { id: string | null; onClose: () => void }) {
  const [log, setLog] = useState<DeveloperLogDetail | null>(null);
  const [error, setError] = useState<string | null>(null);
  useEffect(() => {
    if (!id) return;
    let live = true;
    setLog(null);
    setError(null);
    getDeveloperLog(id).then(
      (res) => live && setLog(res),
      (err: unknown) => live && setError(errorText(err)),
    );
    const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose();
    document.addEventListener('keydown', onKey);
    return () => {
      live = false;
      document.removeEventListener('keydown', onKey);
    };
  }, [id, onClose]);
  if (!id) return null;

  let body: ReactNode;
  if (error) body = <p className="sk-muted">{error}</p>;
  else if (!log) body = <p className="sk-muted">Loading…</p>;
  else {
    body = (
      <>
        <dl className="dv-facts">
          <dt>Status</dt>
          <dd>
            <StatusChip code={log.statusCode} />
          </dd>
          <dt>Request</dt>
          <dd className="su-mono">
            {log.method} {log.route}
          </dd>
          <dt>Time</dt>
          <dd>{when(log.createdAt)}</dd>
          <dt>Duration</dt>
          <dd>{log.durationMs.toLocaleString()} ms</dd>
          <dt>App or key</dt>
          <dd>
            {log.credential.name}
            <span className="sk-muted"> · {KIND_LABEL[log.credential.kind]}</span>
          </dd>
          <dt>Client IP</dt>
          <dd>{log.ip ?? '—'}</dd>
          <dt>Trace ID</dt>
          <dd className="su-mono">{log.traceId ?? '—'}</dd>
        </dl>
        {log.details ? (
          <>
            <Block title="Request URL" text={log.details.url} />
            <Block title="Request headers" text={headerText(log.details.requestHeaders)} />
            <Block title="Request body" text={log.details.requestBody} />
            <Block title="Response headers" text={headerText(log.details.responseHeaders)} />
            <Block title="Response body" text={log.details.responseBody} />
          </>
        ) : (
          <p className="dv-note">
            {log.statusCode >= 400
              ? 'The request and response of this call were not saved (calls before 20 Nov 2026 have none).'
              : 'Request and response bodies are saved for failed calls (4xx and 5xx) only.'}
          </p>
        )}
      </>
    );
  }

  return (
    <div className="dv-drawer-backdrop" onClick={onClose}>
      <aside
        className="dv-drawer"
        role="dialog"
        aria-modal="true"
        aria-label="API call details"
        onClick={(e) => e.stopPropagation()}
      >
        <header className="dv-drawer-head">
          <h2>API call details</h2>
          <button
            type="button"
            className="icon-btn icon-btn--ghost"
            aria-label="Close"
            onClick={onClose}
          >
            {ICON.close}
          </button>
        </header>
        <div className="dv-drawer-body">{body}</div>
      </aside>
    </div>
  );
}

/** The page heading of a Development page. */
export function DevHead({
  title,
  intro,
  actions,
}: {
  title: string;
  intro: ReactNode;
  actions?: ReactNode;
}) {
  return (
    <header className="dv-head">
      <div>
        <h1>{title}</h1>
        <p>{intro}</p>
      </div>
      {actions ? <div className="dv-head-actions">{actions}</div> : null}
    </header>
  );
}
