'use client';

import { useRef, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  isLegacyScope,
  updatePrivateApp,
  type PrivateApp,
} from '@/features/private-apps/api.client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { orderScopes, scopeLabel } from '../service-keys/data';
import { ScopeDrawer, useScopeCatalog } from '../service-keys/ScopeDrawer';
import { useConfirm } from './ui';
import { WebhookEditor, type WebhookSaver } from './WebhookEditor';

/**
 * Edit app (6 Nov design: app-sync-edit.php): Basic info (name, description), Scopes (HubSpot
 * picker; selected scopes with Delete) and Webhooks. "Commit changes" saves the name,
 * description and scopes (PATCH /private-apps/:id) and the webhook's URL and throttling;
 * event subscriptions are saved as they are made.
 */

export type EditTab = 'basic' | 'scopes' | 'webhooks';

const NAME_MAX = 100;
const DESCRIPTION_MAX = 120;

const svg = (d: React.ReactNode, cls?: string) => (
  <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
    {d}
  </svg>
);
const TAB_ICONS: Record<EditTab, React.ReactNode> = {
  basic: svg(
    <>
      <circle cx="12" cy="12" r="3" />
      <path d="M12 2v3m0 14v3M4.2 4.2l2.1 2.1m11.4 11.4 2.1 2.1M2 12h3m14 0h3M4.2 19.8l2.1-2.1M17.7 6.3l2.1-2.1" />
    </>,
    'ase-tab__icon',
  ),
  scopes: svg(
    <>
      <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
      <polyline points="9 12 11 14 15 10" />
    </>,
    'ase-tab__icon',
  ),
  webhooks: svg(<polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" />, 'ase-tab__icon'),
};
const TAB_LABELS: Record<EditTab, string> = {
  basic: 'Basic info',
  scopes: 'Scopes',
  webhooks: 'Webhooks',
};

export function AppEdit({
  app,
  initialTab = 'basic',
  onBack,
  onSaved,
}: {
  app: PrivateApp;
  initialTab?: EditTab;
  onBack: () => void;
  onSaved: (app: PrivateApp) => void;
}) {
  const toast = useToast();
  const [ask, confirmElement] = useConfirm();
  const { catalog, error: catalogError } = useScopeCatalog();
  const [tab, setTab] = useState<EditTab>(initialTab);
  const [name, setName] = useState(app.name);
  const [description, setDescription] = useState(app.description ?? '');
  const [scopes, setScopes] = useState<string[]>(app.scopes);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const nameRef = useRef<HTMLInputElement>(null);
  const webhook = useRef<WebhookSaver>(null);

  const ordered = orderScopes(scopes, catalog);
  const sameScopes = ordered.join('\n') === orderScopes(app.scopes, catalog).join('\n');
  const desc = description.trim() || null;
  const appDirty = name.trim() !== app.name || desc !== app.description || !sameScopes;
  const dirty = () => appDirty || Boolean(webhook.current?.dirty());

  const commit = async () => {
    const trimmed = name.trim();
    if (!trimmed) {
      setTab('basic');
      setError('Enter a name for this app.');
      nameRef.current?.focus();
      return;
    }
    if (!scopes.length) {
      setTab('scopes');
      setError('Select at least one scope.');
      return;
    }
    if (!dirty()) {
      toast('Nothing to save', 'info');
      return;
    }
    setError(null);
    setSaving(true);
    try {
      if (appDirty) {
        const body: { name?: string; description?: string | null; scopes?: string[] } = {};
        if (trimmed !== app.name) body.name = trimmed;
        if (desc !== app.description) body.description = desc;
        if (!sameScopes) body.scopes = ordered;
        onSaved(await updatePrivateApp(app.id, body));
      }
      if (webhook.current?.dirty() && !(await webhook.current.save())) {
        setTab('webhooks');
        setError('The webhook was not saved: check its target URL and event throttling.');
        return;
      }
      toast('Changes saved', 'success');
    } catch (err) {
      setError(errorText(err));
    } finally {
      setSaving(false);
    }
  };

  const back = async () => {
    if (dirty()) {
      const a = await ask(
        'Discard unsaved changes?',
        <p>Your changes to {app.name} haven&apos;t been committed yet.</p>,
        [{ label: 'Keep editing' }, { label: 'Discard changes', primary: true }],
      );
      if (a !== 1) return;
    }
    onBack();
  };

  return (
    <div className="ase-page">
      <header className="ase-topbar">
        <div className="ase-topbar__left">
          <a
            href="#"
            className="ase-back-link"
            onClick={(e) => {
              e.preventDefault();
              void back();
            }}
          >
            {svg(<path d="m15 18-6-6 6-6" />)}
            <span>Back</span>
          </a>
        </div>
        <div className="ase-topbar__center">
          <div
            className="ase-title-wrap"
            title="Click to rename app"
            onClick={() => {
              setTab('basic');
              setTimeout(() => nameRef.current?.focus(), 0);
            }}
          >
            <span className="ase-title">{name.trim() || app.name}</span>
            <button type="button" className="ase-title-edit-btn" aria-label="Edit app name">
              {svg(<path d="M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z" />)}
            </button>
          </div>
        </div>
        <div className="ase-topbar__right">
          <button
            type="button"
            className="btn-crm btn-crm--primary ase-commit-btn"
            disabled={saving}
            onClick={() => void commit()}
          >
            {saving ? 'Saving…' : 'Commit changes'}
          </button>
        </div>
      </header>

      <div className="ase-subnav">
        <div className="ase-subnav__left" />
        <div className="ase-subnav__center">
          <nav className="ase-tabs" aria-label="Edit app tabs" role="tablist">
            {(['basic', 'scopes', 'webhooks'] as const).map((t) => (
              <button
                key={t}
                type="button"
                role="tab"
                className={cn('ase-tab', tab === t && 'is-active')}
                data-ase-tab={t}
                aria-selected={tab === t}
                onClick={() => setTab(t)}
              >
                {TAB_ICONS[t]}
                <span>{TAB_LABELS[t]}</span>
              </button>
            ))}
          </nav>
        </div>
        <div className="ase-subnav__right" />
      </div>

      {/* QA #933: the page is already inside the app's <main>. */}
      <div className="ase-content-container">
        {error ? (
          <div className="ase-banner ase-banner--danger" role="alert">
            <div className="ase-banner__content">
              {svg(
                <>
                  <circle cx="12" cy="12" r="10" />
                  <line x1="12" y1="8" x2="12" y2="12" />
                  <line x1="12" y1="16" x2="12.01" y2="16" />
                </>,
                'ase-banner__icon',
              )}
              <div className="ase-banner__text">
                <strong>Something went wrong when saving your changes.</strong>
                <span>{error}</span>
              </div>
            </div>
            <button
              type="button"
              className="ase-banner__close"
              aria-label="Close"
              onClick={() => setError(null)}
            >
              {svg(<path d="m6 6 12 12M18 6 6 18" />)}
            </button>
          </div>
        ) : null}

        <div className={cn('ase-tab-panel', tab === 'basic' && 'is-active')} role="tabpanel">
          <h2 className="ase-section-title">Basic Info</h2>
          <p className="ase-section-desc">
            Give your app a unique name and description to help your team understand what it does.
          </p>
          <form noValidate onSubmit={(e) => e.preventDefault()}>
            <div className="ase-field-group">
              <label htmlFor="ase-app-name" className="ase-label">
                Name <span className="ase-required">*</span>
              </label>
              <p className="ase-help-text">
                This name will appear in your legacy apps page, some CRM tools, and other material.
              </p>
              <input
                ref={nameRef}
                type="text"
                className="ase-input"
                id="ase-app-name"
                value={name}
                maxLength={NAME_MAX}
                required
                onChange={(e) => setName(e.target.value)}
              />
              <div className="ase-counter">
                <span>{NAME_MAX - name.length}</span> characters remaining
              </div>
            </div>
            <div className="ase-field-group">
              <label htmlFor="ase-app-desc" className="ase-label">
                Description
              </label>
              <textarea
                className="ase-textarea"
                id="ase-app-desc"
                rows={4}
                placeholder="Provide a description for your app"
                maxLength={DESCRIPTION_MAX}
                value={description}
                onChange={(e) => setDescription(e.target.value)}
              />
              <div className="ase-counter">
                <span>{DESCRIPTION_MAX - description.length}</span> characters remaining
              </div>
            </div>
          </form>
        </div>

        <div className={cn('ase-tab-panel', tab === 'scopes' && 'is-active')} role="tabpanel">
          <h2 className="ase-section-title">Scopes</h2>
          <p className="ase-section-desc">
            Scopes determine what your app can access and do in CRM. It&apos;s strongly encouraged
            to require as few scopes as possible for your app&apos;s functionality.
          </p>
          <div className="ase-scopes-header">
            <h3 className="ase-sub-title">Selected scopes</h3>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setDrawerOpen(true)}
            >
              {svg(<path d="M12 5v14M5 12h14" />)}
              <span>Add new scope</span>
            </button>
          </div>
          <div className="ase-scopes-list">
            {!ordered.length ? (
              <p className="crm-text-muted crm-fs-7" style={{ padding: '16px 0' }}>
                No scopes selected. Add scopes to grant API capabilities.
              </p>
            ) : (
              ordered.map((scope) => {
                const legacy = isLegacyScope(scope);
                return (
                  <div key={scope} className="ase-scope-row" title={scopeLabel(scope, catalog)}>
                    <code className="ase-scope-badge">{scope}</code>
                    {legacy ? (
                      <span className="sk-muted">Older name: kept as it is</span>
                    ) : (
                      <button
                        type="button"
                        className="ase-scope-del-btn"
                        onClick={() => setScopes((cur) => cur.filter((s) => s !== scope))}
                      >
                        Delete
                      </button>
                    )}
                  </div>
                );
              })
            )}
          </div>
        </div>

        <div className={cn('ase-tab-panel', tab === 'webhooks' && 'is-active')} role="tabpanel">
          <WebhookEditor
            owner={{ kind: 'private_app', id: app.id }}
            ownerLabel="app"
            scopes={app.effectiveScopes}
            saveRef={webhook}
          />
        </div>
      </div>

      {drawerOpen ? (
        <ScopeDrawer
          catalog={catalog}
          catalogError={catalogError}
          selected={scopes}
          onApply={(next) => {
            setScopes(next);
            setDrawerOpen(false);
          }}
          onClose={() => setDrawerOpen(false)}
        />
      ) : null}

      {confirmElement}
    </div>
  );
}
