'use client';

import { useCallback, useEffect, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import {
  createPersonalAccessKey,
  deletePersonalAccessKey,
  getPersonalAccessKey,
  getPersonalAccessKeyToken,
  PERSONAL_KEY_PERMISSIONS,
  type PersonalAccessKey,
  type PersonalKeyPermission,
} 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 { DevHead } from './shared';
import './development.css';

/**
 * The 16 personal access key permissions of design personal-access-key.php (HubSpot's set, in
 * the design's order; sheet 25 Nov). `value`
 * is the CRM permission behind it; the rest are HubSpot tools the CRM doesn't have, shown off.
 */
const HUBSPOT_PERMISSIONS: { label: string; help: string; value?: PersonalKeyPermission }[] = [
  { label: 'Domains', help: 'List account domains.' },
  { label: 'CMS Pages', help: 'View and download website data.' },
  { label: 'CRM Objects', help: 'Read data from CRM objects.', value: 'crm_objects' },
  {
    label: 'Custom Objects',
    help: 'Create, delete, or make changes to custom objects in the CRM.',
    value: 'custom_objects',
  },
  {
    label: 'Design Manager',
    help: 'Upload and download templates, modules, and other files for websites and emails.',
  },
  {
    label: 'Developer Platform Logs',
    help: 'Read API call logs and usage of this account.',
    value: 'developer_logs',
  },
  { label: 'Developer Projects', help: 'Upload and download developer projects.' },
  { label: 'Developer App Secrets', help: 'Create, update, and delete app secrets.' },
  { label: 'Developer Test Accounts', help: 'Create, update, and delete developer test accounts.' },
  {
    label: 'Serverless functions',
    help: 'View logs, manage secrets, and interact with other serverless functionality.',
  },
  { label: 'Public endpoints', help: 'Create public endpoints.' },
  { label: 'App functions', help: 'Create named functions to be used by private apps.' },
  {
    label: 'File Manager',
    help: 'Upload and download files used across tools when creating content.',
  },
  { label: 'GraphQL Data Fetching', help: 'Execute GraphQL queries and fetch GraphQL Schema.' },
  { label: 'Sandboxes', help: 'Create, update, and delete sandboxes.' },
];

/**
 * Development › Keys › Personal Access Key (HUB-318, HUB-745 QA #728; design
 * settings-personal-access-key.php): your own API key in this account. It calls as you (your
 * role and record access), limited to the permissions picked. HubSpot lists 16 permissions; the
 * CRM offers the ones it has features for.
 */
export function PersonalKeyView() {
  const toast = useToast();
  const me = useCurrentUser();
  const isAdmin = me.permissionSet.rules.app.manage_settings;
  const [ask, confirmElement] = useConfirm();
  const [key, setKey] = useState<PersonalAccessKey | null | undefined>(undefined);
  const [error, setError] = useState<string | null>(null);
  const [editing, setEditing] = useState(false);
  const [name, setName] = useState('Personal Access Key');
  const [picked, setPicked] = useState<PersonalKeyPermission[]>(['crm_objects']);
  const [busy, setBusy] = useState(false);
  const load = useCallback(() => getPersonalAccessKeyToken(), []);
  const secret = useSecret(load, 'This key cannot be shown: generate a new one.');

  useEffect(() => {
    getPersonalAccessKey().then(
      (res) => {
        setKey(res.key);
        if (res.key) {
          setName(res.key.name);
          setPicked(res.key.permissions);
        }
      },
      (err: unknown) => setError(errorText(err)),
    );
  }, []);

  const toggle = (value: PersonalKeyPermission) =>
    setPicked((cur) => (cur.includes(value) ? cur.filter((p) => p !== value) : [...cur, value]));

  const generate = async () => {
    if (key) {
      const choice = await ask(
        'Generate a new personal access key?',
        <p>Your current key stops working at once. Tools using it need the new key.</p>,
        [{ label: 'Cancel' }, { label: 'Generate new key', primary: true }],
      );
      if (choice !== 1) return;
    }
    setBusy(true);
    try {
      const created = await createPersonalAccessKey({
        name: name.trim() || 'Personal Access Key',
        permissions: picked,
      });
      const { token, ...rest } = created;
      setKey(rest);
      secret.replace(token);
      setEditing(false);
      toast('Personal access key generated. Copy it now and keep it somewhere safe.', 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  const remove = async () => {
    const choice = await ask(
      'Delete your personal access key?',
      <p>The key stops working at once. This can&apos;t be undone.</p>,
      [{ label: 'Cancel' }, { label: 'Delete key', primary: true }],
    );
    if (choice !== 1) return;
    setBusy(true);
    try {
      await deletePersonalAccessKey();
      setKey(null);
      secret.replace(null);
      toast('Personal access key deleted', 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  const head = (
    <DevHead
      title="Personal Access Key"
      intro="Your own key for scripts and developer tools in this account. It acts as you: it can only do what you can do, within the permissions you pick."
    />
  );
  if (error || key === undefined) {
    return (
      <div className="dv-page">
        {head}
        <p className="sk-muted">{error ?? 'Loading…'}</p>
      </div>
    );
  }

  const showForm = key === null || editing;

  return (
    <div className="dv-page dv-pat">
      {head}
      <div className="dv-callout dv-callout--info">
        <span>
          This key is personal: anything done with it is recorded as done by you. Don&apos;t share
          it, and delete it when you no longer need it. It stops if you leave this account.
        </span>
      </div>

      {key && !editing ? (
        <section className="sk-detail-card">
          <div className="sk-detail-card-heading">
            <h2>{key.name}</h2>
            <div className="dv-head-actions">
              <button
                type="button"
                className="btn-crm btn-crm--outline"
                disabled={busy}
                onClick={() => setEditing(true)}
              >
                Generate new key
              </button>
              <button
                type="button"
                className="btn-crm btn-crm--outline sk-danger-btn"
                disabled={busy}
                onClick={() => void remove()}
              >
                Delete
              </button>
            </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>
          <dl className="dv-facts dv-facts--inline">
            <dt>Created</dt>
            <dd>{ago(key.createdAt)}</dd>
            <dt>Last used</dt>
            <dd>{when(key.lastUsedAt)}</dd>
            <dt>Permissions</dt>
            <dd>
              {key.permissions
                .map((p) => PERSONAL_KEY_PERMISSIONS.find((o) => o.value === p)?.label ?? p)
                .join(', ')}
            </dd>
          </dl>
        </section>
      ) : null}

      {showForm ? (
        <form
          className="sk-detail-card dv-pat-form"
          onSubmit={(e) => {
            e.preventDefault();
            void generate();
          }}
        >
          <div className="sk-field">
            <label htmlFor="pat-name">Key name</label>
            <input
              id="pat-name"
              className="input"
              maxLength={100}
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
          </div>
          <h2>Permissions</h2>
          <p className="sk-help">Pick what the key may be used for.</p>
          <div className="dv-perm-grid">
            {HUBSPOT_PERMISSIONS.map((p) => {
              const value = p.value;
              const adminOnly = value === 'developer_logs' && !isAdmin;
              const off = !value || adminOnly;
              return (
                <label key={p.label} className={`dv-perm ${off ? 'is-disabled' : ''}`}>
                  <input
                    type="checkbox"
                    checked={value ? picked.includes(value) : false}
                    disabled={off}
                    onChange={() => value && toggle(value)}
                  />
                  <span>
                    <strong>{p.label}</strong>
                    <small>
                      {!value
                        ? `${p.help} Not available in the CRM yet.`
                        : adminOnly
                          ? 'Only admins can read the developer logs.'
                          : p.help}
                    </small>
                  </span>
                </label>
              );
            })}
          </div>
          <div className="dv-sticky-actions">
            {key ? (
              <button
                type="button"
                className="btn-crm btn-crm--outline"
                onClick={() => setEditing(false)}
              >
                Cancel
              </button>
            ) : null}
            <button
              type="submit"
              className="btn-crm btn-crm--primary"
              disabled={busy || !picked.length}
            >
              {busy ? 'Generating…' : 'Generate personal access key'}
            </button>
          </div>
        </form>
      ) : null}
      {confirmElement}
    </div>
  );
}
