'use client';

import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { useCallback, useEffect, useState } from 'react';
import { listAllPrivateApps, type PrivateApp } from '@/features/private-apps/api.client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { AppDetail, type Tab } from './AppDetail';
import { AppEdit, type EditTab } from './AppEdit';
import { CreateLegacyAppForm } from './CreateLegacyApp';
import {
  APP_TYPE,
  LIST_COLUMNS,
  downloadCsv,
  listRow,
  updatedAtOf,
  when,
  type AppType,
} from './data';
import { ICON, LaModal, S, useConfirm } from './ui';

/**
 * Settings › Integrations › Legacy Apps (4 Nov design: settings-legacy-apps.php). In HubSpot
 * "legacy apps" are the old token-based private apps, so this lists the business's private-app
 * tokens (GET /private-apps; deleted apps are left out) and opens an app's page
 * (`?app=<id>`, 6 Nov design app-sync-details: Overview, Auth, Logs, Webhooks) and its Edit app
 * page (`?app=<id>&edit=1`, app-sync-edit: Basic info, Scopes, Webhooks). "Create legacy app"
 * makes a private app, or points to Service Keys (HUB-745, QA #922).
 */

const DETAIL_TABS: readonly Tab[] = ['overview', 'auth', 'logs', 'webhooks'];
const EDIT_TABS: readonly EditTab[] = ['basic', 'scopes', 'webhooks'];

export function LegacyAppsView() {
  const [ask, confirmElement] = useConfirm();
  const router = useRouter();
  const pathname = usePathname();
  const params = useSearchParams();
  const [apps, setApps] = useState<PrivateApp[] | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);
  const activeId = params.get('app');
  const editing = params.get('edit') === '1';
  const tabParam = params.get('tab') ?? '';
  const [search, setSearch] = useState('');
  const [filterType, setFilterType] = useState<'' | AppType>('');
  const [filterOpen, setFilterOpen] = useState(false);
  const [createOpen, setCreateOpen] = useState(false);
  /** HUB-745 (QA #922): the dialog's private app form instead of its choices. */
  const [createForm, setCreateForm] = useState(false);

  const load = useCallback(() => {
    setLoadError(null);
    listAllPrivateApps().then(setApps, (err: unknown) => setLoadError(errorText(err)));
  }, []);
  useEffect(load, [load]);

  const app = apps?.find((a) => a.id === activeId) ?? null;
  const q = search.trim().toLowerCase();
  const visible = (apps ?? []).filter(
    (a) =>
      (!q ||
        a.name.toLowerCase().includes(q) ||
        (a.description ?? '').toLowerCase().includes(q) ||
        a.tokenPrefix.toLowerCase().includes(q)) &&
      (!filterType || filterType === APP_TYPE),
  );

  /** Opens the list, an app's page or its Edit app page (in the URL, so Back works). */
  const show = (id: string | null, edit = false, tab?: string) => {
    const q = new URLSearchParams();
    if (id) q.set('app', id);
    if (id && edit) q.set('edit', '1');
    if (id && tab) q.set('tab', tab);
    const query = q.toString();
    router.push(query ? `${pathname}?${query}` : pathname);
    window.scrollTo({ top: 0, behavior: 'auto' });
  };
  const replaceApp = (next: PrivateApp) =>
    setApps((cur) => (cur ?? []).map((a) => (a.id === next.id ? next : a)));
  const learn = (e: React.MouseEvent) => {
    e.preventDefault();
    void ask(
      'Legacy app migration',
      <p>
        Legacy apps are private apps with one access token. New integrations should use service
        keys; a legacy app can still be created for tools that need a private-app token. Existing
        tokens keep working until you delete the app.
      </p>,
      [{ label: 'Got it', primary: true }],
    );
  };

  // A click outside the type filter closes it.
  useEffect(() => {
    if (!filterOpen) return;
    const onClick = (e: MouseEvent) => {
      if (!(e.target as Element | null)?.closest('.la-filter')) setFilterOpen(false);
    };
    document.addEventListener('click', onClick);
    return () => document.removeEventListener('click', onClick);
  }, [filterOpen]);

  // Exactly what the table shows: same columns, labels and date text (QA #441).
  const exportCsv = () => {
    const now = new Date();
    downloadCsv('legacy-apps.csv', [
      [...LIST_COLUMNS],
      ...visible.map((a) => {
        const row = listRow(a, now);
        return [row.app, row.appId, row.updated, row.lastUsed, row.type, row.project, row.status];
      }),
    ]);
  };

  /**
   * The Service key card of "Create legacy app" (QA #430; sheet 25 Nov): opens the Create service
   * key form, as design service-keys.php?action=create.
   */
  const openServiceKeys = () => {
    setCreateOpen(false);
    router.push('/settings/service-keys?new=1');
  };

  const filtered = Boolean(q || filterType);

  return (
    <>
      <section className="la-view" hidden={app !== null}>
        <header className="la-page-head">
          <h1>Legacy Apps</h1>
          <button
            className="btn-crm btn-crm--primary"
            type="button"
            onClick={() => setCreateOpen(true)}
          >
            Create legacy app
          </button>
        </header>
        <div className="la-toolbar">
          <label className="la-search">
            <span className="la-sr-only">Search for an app</span>
            <input
              type="search"
              placeholder="Search for an app"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
            />
            <span className="la-search-icon">{ICON.search}</span>
            <button
              type="button"
              hidden={!q}
              aria-label="Clear search"
              onClick={() => setSearch('')}
            >
              {ICON.close}
            </button>
          </label>
          <div style={{ display: 'flex', alignItems: 'center', gap: 20 }}>
            <button
              type="button"
              className="la-export"
              disabled={!visible.length}
              onClick={exportCsv}
            >
              {ICON.download} Export (CSV)
            </button>
            <div className="la-filter">
              <button
                type="button"
                aria-expanded={filterOpen}
                onClick={() => setFilterOpen((v) => !v)}
              >
                {filterType || 'Filter by app type'}
                <i />
              </button>
              <div className="la-filter-menu" hidden={!filterOpen}>
                {(['Public', 'Private'] as const).map((type) => (
                  <button
                    key={type}
                    type="button"
                    className={cn(filterType === type && 'is-selected')}
                    onClick={() => {
                      setFilterType((cur) => (cur === type ? '' : type));
                      setFilterOpen(false);
                    }}
                  >
                    {type}
                  </button>
                ))}
              </div>
            </div>
          </div>
        </div>
        <div className="la-table-wrap" hidden={visible.length === 0}>
          <table className="la-table">
            <thead>
              {/* HubSpot's Legacy apps list (QA #429, #934). */}
              <tr>
                {LIST_COLUMNS.map((c) => (
                  <th key={c}>{c}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {visible.map((a) => {
                const row = listRow(a);
                return (
                  <tr key={a.id}>
                    <td>
                      <button type="button" className="la-app-link" onClick={() => show(a.id)}>
                        {row.app}
                      </button>
                    </td>
                    <td>
                      <code className="la-app-id" title={row.appId}>
                        {row.appId.slice(0, 8)}…
                      </code>
                    </td>
                    <td style={S.keep} title={when(updatedAtOf(a))}>
                      {row.updated}
                    </td>
                    <td style={S.keep} title={a.lastUsedAt ? when(a.lastUsedAt) : undefined}>
                      {row.lastUsed}
                    </td>
                    <td>{row.type}</td>
                    <td>{row.project}</td>
                    <td>
                      <span
                        className={a.revokedAt ? 'badge badge--danger' : 'badge badge--success'}
                        title={a.revokedAt ? when(a.revokedAt) : undefined}
                      >
                        {row.status}
                      </span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        <div className="la-empty" hidden={visible.length !== 0}>
          <div>{ICON.empty}</div>
          <section>
            {loadError ? (
              <>
                <h2>Couldn&apos;t load legacy apps</h2>
                <p>{loadError}</p>
                <button type="button" className="btn-crm btn-crm--outline" onClick={load}>
                  Try again
                </button>
              </>
            ) : apps === null ? (
              <>
                <h2>Loading legacy apps…</h2>
                <p>One moment.</p>
              </>
            ) : filtered && apps.length ? (
              <>
                <h2>No apps match your search</h2>
                <p>
                  {filterType === 'Public'
                    ? 'This CRM has no public apps: every legacy app here is a private app with an access token.'
                    : 'Change your search or filter and try again.'}
                </p>
                <a
                  href="#"
                  onClick={(e) => {
                    e.preventDefault();
                    setSearch('');
                    setFilterType('');
                  }}
                >
                  Clear search and filter
                </a>
              </>
            ) : (
              <>
                <h2>No legacy apps available</h2>
                <p>This is actually a good thing! New integrations should use service keys.</p>
                <a href="#" onClick={learn}>
                  Learn more {ICON.ext}
                </a>
              </>
            )}
          </section>
        </div>
      </section>

      <section className="la-view la-detail" hidden={app === null}>
        {app && editing ? (
          <AppEdit
            key={`${app.id}-edit`}
            app={app}
            initialTab={EDIT_TABS.find((t) => t === tabParam) ?? 'basic'}
            onBack={() => show(app.id)}
            onSaved={replaceApp}
          />
        ) : app ? (
          <AppDetail
            key={app.id}
            app={app}
            initialTab={DETAIL_TABS.find((t) => t === tabParam) ?? 'overview'}
            onBack={() => show(null)}
            onEdit={(tab) => show(app.id, true, tab)}
            onChange={replaceApp}
            onDeleted={(id) => {
              setApps((cur) => (cur ?? []).filter((a) => a.id !== id));
              show(null);
            }}
          />
        ) : null}
      </section>

      {/* Create legacy app (HUB-745, QA #922): a private app, or a service key. */}
      <LaModal
        open={createOpen}
        title={createForm ? 'Create legacy private app' : 'Create legacy app'}
        onClose={() => {
          setCreateOpen(false);
          setCreateForm(false);
        }}
      >
        {createForm ? (
          <CreateLegacyAppForm
            onCancel={() => setCreateForm(false)}
            onCreated={(created) => {
              setApps((cur) => [created, ...(cur ?? [])]);
              setCreateOpen(false);
              setCreateForm(false);
              show(created.id, false, 'auth');
            }}
          />
        ) : (
          <div className="la-modal-body">
            <div className="la-info-box">
              New integrations should use a service key. Create a legacy private app only for tools
              that need a private-app access token.
            </div>
            <div className="la-choice-grid">
              <button
                type="button"
                className="la-choice"
                style={{ background: 'var(--surface)', font: 'inherit', cursor: 'pointer' }}
                onClick={openServiceKeys}
              >
                <strong>Service key</strong>
                <span>Call the CRM API from your own code or scripts.</span>
                <i />
                <small>Recommended. Replaces legacy private apps.</small>
              </button>
              <button
                type="button"
                className="la-choice"
                style={{ background: 'var(--surface)', font: 'inherit', cursor: 'pointer' }}
                onClick={() => setCreateForm(true)}
              >
                <strong>Legacy private app</strong>
                <span>One access token with the scopes you pick, and an optional webhook.</span>
                <i />
                <small>For tools that need a private-app token.</small>
              </button>
            </div>
            <a
              href="#"
              className="la-learn"
              onClick={(e) => {
                setCreateOpen(false);
                learn(e);
              }}
            >
              Learn more about service keys and legacy apps {ICON.ext}
            </a>
          </div>
        )}
      </LaModal>

      {confirmElement}
    </>
  );
}
