'use client';

import Link from 'next/link';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  createDeveloperApiKey,
  getDeveloperApiKey,
  getDeveloperApiKeyToken,
  rotateDeveloperApiKey,
  setDeveloperApiKeyActive,
  type DeveloperApiKey,
} from '@/features/developer/api.client';
import { errorText } from '@/lib/api/errors';
import { ago, when } from '../legacy-apps/data';
import { useConfirm } from '../legacy-apps/ui';
import { maskSecret, useSecret } from '../service-keys/useSecret';
import { SuBadge } from '../settings-ui';
import { DevHead } from './shared';
import './development.css';

/**
 * Development › Keys › Developer API Key (HUB-188, HUB-745 QA #727; design
 * settings-developer-api-key.php): the account's one developer key, admins only. Show / copy,
 * rotate (now or keeping the old key 24 hours), deactivate / activate (no delete, as in
 * HubSpot); each is in the
 * audit log. The key reads the account's API logs and usage only.
 */
export function DeveloperKeyView() {
  const toast = useToast();
  const [ask, confirmElement] = useConfirm();
  const [key, setKey] = useState<DeveloperApiKey | null | undefined>(undefined);
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);
  const load = useCallback(() => getDeveloperApiKeyToken(), []);
  const secret = useSecret(load, 'This key cannot be shown: rotate it to see the new key.');

  useEffect(() => {
    getDeveloperApiKey().then(
      (res) => setKey(res.key),
      (err: unknown) => setError(errorText(err)),
    );
  }, []);
  useEffect(() => {
    if (!menuOpen) return;
    const onClick = (e: MouseEvent) => {
      if (!menuRef.current?.contains(e.target as Node)) setMenuOpen(false);
    };
    document.addEventListener('click', onClick);
    return () => document.removeEventListener('click', onClick);
  }, [menuOpen]);

  const run = async (work: () => Promise<void>) => {
    setBusy(true);
    setMenuOpen(false);
    try {
      await work();
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  const create = () =>
    run(async () => {
      const created = await createDeveloperApiKey();
      const { token, ...rest } = created;
      setKey(rest);
      secret.replace(token);
      toast('Developer API key created. Copy it now and keep it somewhere safe.', 'success');
    });

  const rotate = async () => {
    const choice = await ask(
      'Rotate the developer API key?',
      <p>
        A new key is made at once. Tools using the current key must be updated: it can stop now, or
        keep working for 24 hours while you switch.
      </p>,
      [
        { label: 'Cancel' },
        { label: 'Keep old key 24 hours' },
        { label: 'Rotate now', primary: true },
      ],
    );
    if (choice !== 1 && choice !== 2) return;
    await run(async () => {
      const rotated = await rotateDeveloperApiKey(choice === 1 ? 24 : 0);
      const { token, ...rest } = rotated;
      setKey(rest);
      secret.replace(token);
      toast(
        choice === 1
          ? 'Key rotated. The old key works for 24 more hours.'
          : 'Key rotated. The old key stopped.',
        'success',
      );
    });
  };

  const toggleActive = async () => {
    if (!key) return;
    const activating = key.status === 'deactivated';
    if (!activating) {
      const choice = await ask(
        'Deactivate the developer API key?',
        <p>Calls with this key are refused until you activate it again.</p>,
        [{ label: 'Cancel' }, { label: 'Deactivate', primary: true }],
      );
      if (choice !== 1) return;
    }
    await run(async () => {
      setKey(await setDeveloperApiKeyActive(activating));
      toast(activating ? 'Key activated' : 'Key deactivated', 'success');
    });
  };

  const head = (
    <DevHead
      title="Developer API Key"
      intro="One key for this account, used by your developer tools to read its API call logs and usage. It can't read or change CRM records. Only admins can see and manage it."
    />
  );

  if (error) {
    return (
      <div className="dv-page">
        {head}
        <p className="sk-muted">{error}</p>
      </div>
    );
  }
  if (key === undefined) {
    return (
      <div className="dv-page">
        {head}
        <p className="sk-muted">Loading…</p>
      </div>
    );
  }

  return (
    <div className="dv-page">
      {head}
      {key === null ? (
        <section className="sk-detail-card sk-empty">
          <strong>No developer API key yet</strong>
          <p>Create the account&apos;s key to call the developer logs and usage endpoints.</p>
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            disabled={busy}
            onClick={() => void create()}
          >
            Create key
          </button>
        </section>
      ) : (
        <section className="sk-detail-card">
          <div className="sk-detail-card-heading">
            <div className="dv-key-status">
              <span className={`dv-dot ${key.status === 'active' ? 'dv-dot--on' : ''}`} />
              <span>
                {key.status === 'active' ? 'Active' : 'Deactivated'} · Created {ago(key.createdAt)}
                {key.createdByName ? ` by ${key.createdByName}` : ''}
              </span>
            </div>
            <div className="dv-head-actions">
              <Link href="/settings/audit-log" className="sk-text-btn">
                View audit logs
              </Link>
              <div className="sk-rotate-wrap" ref={menuRef}>
                <button
                  type="button"
                  className="btn-crm btn-crm--outline"
                  aria-expanded={menuOpen}
                  disabled={busy}
                  onClick={() => setMenuOpen((v) => !v)}
                >
                  Actions
                  <svg viewBox="0 0 24 24" aria-hidden="true">
                    <path d="m9 18 6-6-6-6" />
                  </svg>
                </button>
                {menuOpen ? (
                  <div className="sk-rotate-menu" role="menu">
                    <button type="button" role="menuitem" onClick={() => void rotate()}>
                      Rotate key
                    </button>
                    <button type="button" role="menuitem" onClick={() => void toggleActive()}>
                      {key.status === 'active' ? 'Deactivate key' : 'Activate key'}
                    </button>
                  </div>
                ) : null}
              </div>
            </div>
          </div>
          <div className="dv-key-box">
            <code className="su-mono">
              {secret.shown && secret.value
                ? secret.value
                : `${key.tokenPrefix}${maskSecret('x'.repeat(36))}`}
            </code>
            <div className="sk-secret-buttons">
              <button
                type="button"
                className="sk-text-btn"
                disabled={secret.loading}
                onClick={() => void secret.toggle()}
              >
                {secret.shown ? 'Hide' : 'Show'}
              </button>
              <button
                type="button"
                className="sk-text-btn"
                disabled={secret.loading}
                onClick={() => void secret.copy()}
              >
                Copy
              </button>
            </div>
          </div>
          {secret.note ? <p className="sk-help">{secret.note}</p> : null}
          <dl className="dv-facts dv-facts--inline">
            <dt>Last used</dt>
            <dd>{when(key.lastUsedAt)}</dd>
            <dt>Last rotated</dt>
            <dd>{when(key.rotatedAt)}</dd>
            {key.previousKeyExpiresAt ? (
              <>
                <dt>Old key works until</dt>
                <dd>
                  <SuBadge tone="warning">{when(key.previousKeyExpiresAt)}</SuBadge>
                </dd>
              </>
            ) : null}
          </dl>
          <p className="sk-help">
            Send it as <code>Authorization: Bearer &lt;key&gt;</code> to{' '}
            <code>GET /api/v1/developer/logs</code> and <code>/developer/usage</code>.
          </p>
        </section>
      )}
      {confirmElement}
    </div>
  );
}
