'use client';

import { useEffect, useMemo, useState, type ReactNode } from 'react';
import {
  getScopeCatalog,
  isLegacyScope,
  type ApiScopeCatalog,
} from '@/features/private-apps/api.client';
import { errorText } from '@/lib/api/errors';
import { orderScopes, scopeLabel } from './data';

/**
 * The scope picker shared by Service Keys and Legacy Apps (HUB-687): HubSpot's scopes from
 * GET /private-apps/scopes, grouped CRM / Standard, in the design's "Add new scope" drawer.
 * Older names (`contacts:read`) on keys and apps made before stay as they are: they can't be
 * picked again, so the drawer keeps them and the chips show them read-only.
 */

const svg = (d: ReactNode) => (
  <svg viewBox="0 0 24 24" aria-hidden="true">
    {d}
  </svg>
);
const CHEVRON = svg(<path d="m9 18 6-6-6-6" />);
const CLOSE = svg(<path d="m6 6 12 12M18 6 6 18" />);
const SEARCH = svg(
  <>
    <circle cx="10.8" cy="10.8" r="6.8" />
    <path d="m16 16 5 5" />
  </>,
);

/** HubSpot's order (Add new scope, 20 Nov); the API sends the groups, this only sorts them. */
const GROUP_ORDER = [
  'CRM',
  'CMS',
  'Automation',
  'Commerce',
  'Communication preferences',
  'Conversations',
  'Data integration',
  'Files',
  'Marketing',
  'Reporting',
  'Settings',
  'Other',
];

/** Scope groups the picker leaves out. */
const HIDDEN_GROUP = 'HubDB';

/** The scope catalog, loaded once; `error` when it could not be read. */
export function useScopeCatalog() {
  const [catalog, setCatalog] = useState<ApiScopeCatalog | null>(null);
  const [error, setError] = useState<string | null>(null);
  useEffect(() => {
    let live = true;
    getScopeCatalog().then(
      (c) => live && setCatalog(c),
      (err: unknown) => live && setError(errorText(err)),
    );
    return () => {
      live = false;
    };
  }, []);
  return { catalog, error };
}

/** Selected scopes as chips; older names are read-only. */
export function ScopeChips({
  scopes,
  catalog,
  onRemove,
  empty = 'No scopes selected',
}: {
  scopes: string[];
  catalog: ApiScopeCatalog | null;
  onRemove?: (scope: string) => void;
  empty?: string;
}) {
  if (!scopes.length) return <p className="sk-muted">{empty}</p>;
  return (
    <>
      {orderScopes(scopes, catalog).map((s) => {
        const legacy = isLegacyScope(s);
        return (
          <span key={s} className="sk-scope-chip" title={scopeLabel(s, catalog) || undefined}>
            <code>{s}</code>
            {legacy ? <span style={{ fontSize: 11, opacity: 0.8 }}>older name</span> : null}
            {onRemove && !legacy ? (
              <button type="button" aria-label={`Remove ${s}`} onClick={() => onRemove(s)}>
                {CLOSE}
              </button>
            ) : null}
          </span>
        );
      })}
    </>
  );
}

/** Mount it when it opens: it starts from `selected` and answers with the new list. */
export function ScopeDrawer({
  catalog,
  catalogError,
  selected,
  onApply,
  onClose,
}: {
  catalog: ApiScopeCatalog | null;
  catalogError: string | null;
  selected: string[];
  onApply: (scopes: string[]) => void;
  onClose: () => void;
}) {
  const [draft, setDraft] = useState<Set<string>>(() => new Set(selected));
  const [search, setSearch] = useState('');
  const [openGroups, setOpenGroups] = useState<Record<string, boolean>>({});

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose();
    document.addEventListener('keydown', onKey);
    document.body.classList.add('sk-modal-open');
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.classList.remove('sk-modal-open');
    };
  }, [onClose]);

  const filter = search.trim().toLowerCase();
  const groups = useMemo(() => {
    const all = catalog?.hubspot ?? [];
    // HUB-745 (QA #926): HubSpot's HubDB has nothing behind it in the CRM; its scopes stay in the
    // catalog (migrated apps may hold them) but are not offered.
    const names = [...new Set([...GROUP_ORDER, ...all.map((s) => s.group)])].filter(
      (g) => g !== HIDDEN_GROUP,
    );
    return names
      .map((group) => ({
        group,
        matches: all.filter(
          (s) =>
            s.group === group &&
            (!filter ||
              s.name.toLowerCase().includes(filter) ||
              s.label.toLowerCase().includes(filter) ||
              group.toLowerCase().includes(filter)),
        ),
      }))
      .filter((g) => g.matches.length);
  }, [catalog, filter]);

  const toggle = (name: string, on: boolean) =>
    setDraft((cur) => {
      const next = new Set(cur);
      if (on) next.add(name);
      else next.delete(name);
      return next;
    });

  return (
    <>
      <div className="sk-overlay" onClick={onClose} />
      <aside
        className="sk-drawer"
        aria-labelledby="sk-drawer-title"
        role="dialog"
        aria-modal="true"
      >
        <header className="sk-drawer-head">
          <h2 id="sk-drawer-title">Add new scope</h2>
          <button type="button" className="sk-icon-btn" aria-label="Close" onClick={onClose}>
            {CLOSE}
          </button>
        </header>
        <div className="sk-drawer-search">
          <label className="sk-sr-only" htmlFor="sk-scope-search">
            Find a scope
          </label>
          {SEARCH}
          <input
            id="sk-scope-search"
            type="search"
            placeholder="Find a scope"
            autoComplete="off"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>
        <div className="sk-scope-categories">
          {catalogError ? (
            <p className="sk-muted crm-mt-3">Couldn&apos;t load the scopes: {catalogError}</p>
          ) : !catalog ? (
            <p className="sk-muted crm-mt-3">Loading scopes…</p>
          ) : null}
          {groups.map(({ group, matches }) => {
            // ~240 scopes: CRM starts open, the other groups closed (as HubSpot); a search opens all.
            const open = openGroups[group] ?? (group === 'CRM' || filter !== '');
            return (
              <section key={group} className={open ? 'sk-scope-group is-open' : 'sk-scope-group'}>
                <button
                  type="button"
                  aria-expanded={open}
                  onClick={() => setOpenGroups((g) => ({ ...g, [group]: !open }))}
                >
                  {CHEVRON}
                  <span>{group}</span>
                </button>
                <div className="sk-scope-options" hidden={!open}>
                  {matches.map(({ name, label, grants }) => (
                    <label key={name} className="sk-scope-option">
                      <span style={{ flex: 1, minWidth: 0 }}>
                        <code>{name}</code>
                        <span className="sk-help crm-d-block crm-mb-0">
                          {label}
                          {grants.length ? null : (
                            <span
                              className="badge sk-scope-unused"
                              style={{ marginLeft: 6 }}
                              title="Accepted and saved, but the CRM API has no endpoints for it yet"
                            >
                              No API access yet
                            </span>
                          )}
                        </span>
                      </span>
                      <input
                        className="form-check-input sk-scope-checkbox"
                        type="checkbox"
                        value={name}
                        checked={draft.has(name)}
                        onChange={(e) => toggle(name, e.target.checked)}
                      />
                    </label>
                  ))}
                </div>
              </section>
            );
          })}
          {catalog && !groups.length ? (
            <p className="sk-muted crm-mt-3">No scopes match your search.</p>
          ) : null}
        </div>
        <footer className="sk-drawer-foot">
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            disabled={!catalog}
            onClick={() => onApply(orderScopes(draft, catalog))}
          >
            Update
          </button>
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
        </footer>
      </aside>
    </>
  );
}
