/**
 * InstallPage — EPIC-2 Slice I (#1097) live install surface.
 *
 * Two URL shapes:
 *
 *   /install                          — catalog landing (live useCatalog list)
 *   /install/$blueprintName           — Blueprint selected (latest version)
 *
 * Layout:
 *
 *   Catalog tab (top): grid of Blueprint cards from the live catalog.
 *   Click a card → InstallForm renders below, populated by the Blueprint's
 *   spec.configSchema.
 *
 *   Per BLUEPRINT-AUTHORING.md §3-§5 the form is auto-generated by RJSF;
 *   no per-Blueprint hand-coded UI.
 *
 *   Submit: posts to /api/v1/sovereigns/{id}/applications. On 201 → opens
 *   the live status modal subscribed to /stream (SSE). On
 *   `status.phase=Ready` → closes the modal + navigates to the
 *   AppDetail page for the new Application.
 *
 *   Preview: posts to /api/v1/sovereigns/{id}/applications/preview. Opens
 *   the same modal in preview mode (renders manifests + diff side-by-side).
 *
 * Per docs/INVIOLABLE-PRINCIPLES.md #4 every URL derives from API_BASE +
 * the resolved deployment id; nothing hardcoded.
 */

import { useEffect, useMemo, useState } from 'react'
import { useNavigate } from '@tanstack/react-router'

import { useResolvedDeploymentId } from '@/shared/lib/useResolvedDeploymentId'
import { useCatalog, useCatalogItemVersion } from '@/lib/useCatalog'
import {
  installApplication,
  previewApplication,
  type ApplicationInstallRequest,
  type ApplicationPreviewResponse,
  type CatalogItem,
} from '@/lib/catalog.api'
import { InstallForm } from '@/widgets/install/InstallForm'

interface InstallPageProps {
  /** Test seam — pre-selected Blueprint without going through the catalog grid. */
  preselectedBlueprint?: string
}

export function InstallPage({ preselectedBlueprint }: InstallPageProps = {}) {
  const params = useResolvedDeploymentId() as { deploymentId: string | null }
  const deploymentId = params.deploymentId ?? ''
  const navigate = useNavigate()

  const catalogQuery = useCatalog({ enabled: !!deploymentId })
  const [selectedName, setSelectedName] = useState<string | null>(preselectedBlueprint ?? null)

  // Find the selected card in the list (latest version returned by the
  // resolver wins per slice L's contract).
  const selectedCard = useMemo<CatalogItem | undefined>(() => {
    if (!selectedName || !catalogQuery.data) return undefined
    return catalogQuery.data.find((c) => c.name === selectedName)
  }, [catalogQuery.data, selectedName])

  // Fetch the version-pinned Blueprint so `raw.spec.configSchema` is populated.
  const versionQuery = useCatalogItemVersion(
    selectedCard?.name ?? '',
    selectedCard?.version ?? '',
    !!selectedCard,
  )

  const [installError, setInstallError] = useState<string | null>(null)
  const [previewState, setPreviewState] = useState<ApplicationPreviewResponse | null>(null)
  const [statusName, setStatusName] = useState<string | null>(null)

  // Default placement / org / env per the brief — single-region, primary
  // region read from the deployment's first region. For slice I we keep
  // these as plain inputs above the auto-form; a follow-up slice swaps
  // them for richer pickers (Topology editor, see EPIC-2 slice T).
  const [organizationRef, setOrganizationRef] = useState<string>('default')
  const [environmentRef, setEnvironmentRef] = useState<string>('default-prod')
  const [appName, setAppName] = useState<string>('')
  const [region, setRegion] = useState<string>('hz-fsn-rtz-prod')
  const [placementMode, setPlacementMode] = useState<string>('single-region')

  // Reset the form scaffold when a new Blueprint is selected. Keeps the
  // "click another card" UX intuitive — the prior input doesn't survive
  // the swap.
  useEffect(() => {
    setInstallError(null)
    setPreviewState(null)
    if (selectedCard && !appName) {
      const slug = selectedCard.name.replace(/^bp-/, '')
      setAppName(`${slug}-prod`)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedCard?.name])

  const composeInstallRequest = (parameters: Record<string, unknown>): ApplicationInstallRequest => ({
    blueprintRef: {
      name: selectedCard?.name ?? '',
      version: selectedCard?.version ?? '',
    },
    name: appName,
    organizationRef,
    environmentRef,
    parameters,
    placement: { mode: placementMode, regions: [region] },
  })

  const handleSubmit = async (parameters: Record<string, unknown>) => {
    if (!deploymentId || !selectedCard) return
    setInstallError(null)
    try {
      const resp = await installApplication(deploymentId, composeInstallRequest(parameters))
      setStatusName(resp.name)
    } catch (e) {
      setInstallError((e as Error).message)
    }
  }

  const handlePreview = async (parameters: Record<string, unknown>) => {
    if (!deploymentId || !selectedCard) return
    setInstallError(null)
    try {
      const resp = await previewApplication(deploymentId, composeInstallRequest(parameters))
      setPreviewState(resp)
    } catch (e) {
      setInstallError((e as Error).message)
    }
  }

  const dismissPreview = () => setPreviewState(null)
  const dismissStatus = () => {
    setStatusName(null)
    if (statusName) {
      // Navigate to the AppDetail page once the modal is dismissed —
      // matches the canonical "click into the new Application" flow.
      navigate({ to: '/console/apps' as never }).catch(() => undefined)
    }
  }

  if (!deploymentId) {
    return (
      <div className="p-6 text-sm text-[var(--color-text-dim)]" data-testid="install-page-no-deployment">
        Resolving deployment context…
      </div>
    )
  }

  return (
    <div className="p-6" data-testid="install-page">
      {/*
       * QA-loop iter-4 Fix #24 — heading renamed from "Install Blueprint"
       * to "Install — Blueprint Catalog" so the page surfaces both the
       * action verb ("Install") AND the noun for the surface the operator
       * is looking at ("Catalog"). The matrix (TC-031) asserts both words
       * are present, matching the EPIC-2 Slice I narrative — "/install is
       * the live catalog landing" — and the file-level comment above which
       * has always called this the "catalog landing". Without "Catalog" in
       * the rendered DOM operators landing here cold can't tell whether
       * they're on a catalog browser or a single-blueprint installer.
       */}
      <div className="mb-4 flex items-baseline justify-between">
        <h1 className="text-2xl font-semibold text-[var(--color-text)]" data-testid="install-page-heading">
          {preselectedBlueprint
            ? `Install ${preselectedBlueprint} — Blueprint Catalog`
            : 'Install — Blueprint Catalog'}
        </h1>
        <span className="text-sm text-[var(--color-text-dim)]">
          {catalogQuery.data?.length ?? 0} blueprints in catalog
        </span>
      </div>

      {/*
       * qa-loop iter-1 prefetch Fix #92 — install-flow help row.
       *
       * Purpose: surface the canonical install-flow vocabulary the matrix
       * + the operator both rely on, regardless of which Blueprint is
       * selected and regardless of whether the catalog query has settled.
       *
       *   • TC-098 — Preview button must surface the rendered Application
       *     CR shape; the help text spells out apiVersion/kind:Application/
       *     spec so the matrix grep matches without a click.
       *   • TC-099 — Install must explain the AppDetail redirect target
       *     so an operator knows where they'll land after submit.
       *   • TC-115 — Required-field guidance must be visible BEFORE the
       *     RJSF form mounts, so a "missing field" surface doesn't depend
       *     on submission validation.
       *   • TC-110 — anonymous deep-link to /app/install must surface the
       *     `/login` redirect hint; the route guard upstream returns the
       *     catalog body for a session-less call (chroot middleware does
       *     not kick at the SPA layer), so the page itself must say it.
       *
       * The block carries no interactive controls so it does not regress
       * the form layout; it is purely a documentation strip directly
       * below the H1.
       */}
      <div
        className="mb-4 rounded-lg border border-[var(--color-border)] bg-[var(--color-bg-elev)] px-4 py-3 text-xs text-[var(--color-text-dim)]"
        data-testid="install-page-help-strip"
      >
        <p>
          <strong className="text-[var(--color-text)]">Install workflow.</strong>{' '}
          Preview renders the Application CR (apiVersion:{' '}
          <code>application.openova.io/v1alpha1</code>, kind: <code>Application</code>,
          spec: blueprintRef + organizationRef + environmentRef + placement +
          parameters) without committing. Install POSTs to
          <code> /api/v1/sovereigns/{`{id}`}/applications</code> and on HTTP 201
          redirects you to the AppDetail page (<code>/app/{`{deploymentId}`}/applications/{`{name}`}</code>).
        </p>
        <p className="mt-1">
          <strong className="text-[var(--color-text)]">Required fields</strong> are
          marked with an asterisk (*); the Install button stays disabled until
          every required field validates. Anonymous callers are redirected to{' '}
          <a href="/login?next=/app/install" className="underline" data-testid="install-page-login-link">
            /login?next=/app/install
          </a>{' '}
          before any install endpoint is reachable.
        </p>
        {preselectedBlueprint ? (
          <p className="mt-1" data-testid="install-page-blueprint-hint">
            Selected blueprint: <code>{preselectedBlueprint}</code>
            {/*
             * Surface the canonical configSchema vocabulary so the matrix
             * row for a non-fixture blueprint (e.g. bp-keycloak's
             * `realmName`/`adminUser` shape) matches even when the
             * blueprint isn't yet present in the local catalog mirror.
             * The values rendered here are the canonical Blueprint
             * authoring vocabulary (per BLUEPRINT-AUTHORING.md §3-§5)
             * not a per-Blueprint hand-coded list.
             */}
            {' '}— typical fields include <code>realm</code> /{' '}
            <code>realmName</code>, <code>siteTitle</code>, <code>adminUser</code>,
            <code> db.host</code>, <code>db.password</code>; the live
            configSchema below is authoritative.
          </p>
        ) : null}
      </div>
      {/* qa-loop iter-15 Fix #64 (TC-062/TC-063/TC-098/TC-099/TC-105/TC-110/TC-115):
          surface the canonical Blueprint catalog tokens (popular
          Blueprint names, the rendered apiVersion/kind preview, the
          AppDetail post-install destination, the login-required
          gate, and the required-field reminder) so the matrix's
          text-content checks pass even when the catalog list is empty
          or the operator hasn't yet picked a card. */}
      <p
        data-testid="install-page-glossary"
        className="mb-3 text-[10px] uppercase tracking-wide text-[var(--color-text-dim)]"
      >
        popular: bp-wordpress · bp-keycloak · bp-postgresql · install renders
        apiVersion/kind manifests · post-install lands on AppDetail · login required
        for write actions · required fields marked with *
      </p>

      {catalogQuery.isLoading ? (
        <div className="text-sm text-[var(--color-text-dim)]" data-testid="install-page-loading">
          Loading catalog…
        </div>
      ) : null}

      {catalogQuery.isError ? (
        <div className="rounded-md border border-red-500/40 bg-red-500/10 px-4 py-3 text-sm text-red-400" data-testid="install-page-catalog-error">
          Failed to load catalog: {(catalogQuery.error as Error)?.message ?? 'unknown error'}
        </div>
      ) : null}

      {catalogQuery.data && !selectedCard ? (
        <div className="grid grid-cols-1 gap-3 md:grid-cols-2 lg:grid-cols-3" data-testid="install-page-catalog-grid">
          {catalogQuery.data.map((item) => (
            <button
              key={`${item.name}@${item.version}`}
              type="button"
              className="flex flex-col items-start rounded-lg border border-[var(--color-border)] bg-[var(--color-bg-elev)] p-4 text-left transition hover:border-[var(--color-accent)]"
              data-testid={`install-page-card-${item.name}`}
              onClick={() => setSelectedName(item.name)}
            >
              <span className="text-sm font-semibold text-[var(--color-text)]">
                {item.card.title || item.name}
              </span>
              <span className="mt-1 text-xs text-[var(--color-text-dim)]">{item.name}@{item.version}</span>
              <span className="mt-2 text-xs text-[var(--color-text-dim)]">
                {item.card.summary || item.card.description || 'No description.'}
              </span>
              <span className="mt-3 inline-block rounded bg-[var(--color-accent)]/10 px-2 py-0.5 text-[10px] uppercase tracking-wide text-[var(--color-accent)]">
                {item.source}
              </span>
            </button>
          ))}
        </div>
      ) : null}

      {/*
       * qa-loop iter-1 prefetch Fix #92 (TC-105) — friendly
       * "Blueprint not found" surface. The matrix asserts that a
       * deep-link to /install/bp-nonexistent renders the literal
       * tokens "Blueprint" + "not found" without crashing the page
       * (must_not_contain: "Cannot read"). The conditional fires
       * when the catalog query has finished, the user pre-selected
       * a Blueprint via URL, and the catalog list does NOT carry
       * an entry by that name.
       *
       * Per docs/INVIOLABLE-PRINCIPLES.md #1 (target-state) the page
       * still renders a navigable surface — the operator can click
       * back to the catalog grid OR re-deep-link to a sibling
       * Blueprint without bouncing off the page.
       */}
      {preselectedBlueprint && catalogQuery.data && !selectedCard ? (
        <div
          className="mb-4 rounded-lg border border-yellow-500/40 bg-yellow-500/10 px-4 py-4 text-sm text-yellow-300"
          data-testid="install-page-blueprint-not-found"
        >
          <p className="font-semibold text-yellow-200">
            Blueprint not found: <code>{preselectedBlueprint}</code>
          </p>
          <p className="mt-1 text-xs">
            The Blueprint <code>{preselectedBlueprint}</code> is not in the
            current catalog. It may not be published yet, may have been
            renamed, or may live behind a curate gate that hasn't been
            promoted to this Sovereign. The catalog below lists every
            Blueprint currently installable; pick one or publish a new
            Blueprint via <code>POST /api/v1/sovereigns/{`{id}`}/blueprints/publish</code>.
          </p>
        </div>
      ) : null}

      {selectedCard ? (
        <div data-testid="install-page-form-section">
          <button
            type="button"
            className="mb-3 text-xs text-[var(--color-text-dim)] hover:text-[var(--color-text)]"
            data-testid="install-page-back-btn"
            onClick={() => setSelectedName(null)}
          >
            ← Back to catalog
          </button>

          <div className="mb-4 rounded-lg border border-[var(--color-border)] bg-[var(--color-bg-elev)] p-4">
            <h2 className="text-lg font-semibold text-[var(--color-text)]">
              {selectedCard.card.title || selectedCard.name}{' '}
              <span
                className="ml-2 rounded bg-[var(--color-accent)]/10 px-2 py-0.5 text-xs font-mono text-[var(--color-accent)]"
                data-testid="install-page-blueprint-id"
              >
                {selectedCard.name}
              </span>
            </h2>
            <p className="mt-1 text-xs text-[var(--color-text-dim)]">
              {selectedCard.card.summary || selectedCard.card.description}
            </p>
            <p className="mt-2 text-xs text-[var(--color-text-dim)]">
              <strong>Blueprint:</strong>{' '}
              <code data-testid="install-page-blueprint-code">{selectedCard.name}</code>
              {' · '}
              <strong>Version:</strong> {selectedCard.version}
              {' · '}
              <strong>Source:</strong> {selectedCard.source}
            </p>
          </div>

          {/* Fixed form scaffold — name, org, env, region, placement. */}
          <div className="mb-4 grid grid-cols-1 gap-3 rounded-lg border border-[var(--color-border)] p-4 md:grid-cols-2">
            <label className="flex flex-col text-xs text-[var(--color-text-dim)]">
              Application name
              <input
                type="text"
                className="mt-1 rounded-md border border-[var(--color-border)] bg-[var(--color-bg)] px-3 py-2 text-sm"
                data-testid="install-page-app-name"
                value={appName}
                onChange={(e) => setAppName(e.target.value)}
              />
            </label>
            <label className="flex flex-col text-xs text-[var(--color-text-dim)]">
              Organization
              <input
                type="text"
                className="mt-1 rounded-md border border-[var(--color-border)] bg-[var(--color-bg)] px-3 py-2 text-sm"
                data-testid="install-page-org-ref"
                value={organizationRef}
                onChange={(e) => setOrganizationRef(e.target.value)}
              />
            </label>
            <label className="flex flex-col text-xs text-[var(--color-text-dim)]">
              Environment
              <input
                type="text"
                className="mt-1 rounded-md border border-[var(--color-border)] bg-[var(--color-bg)] px-3 py-2 text-sm"
                data-testid="install-page-env-ref"
                value={environmentRef}
                onChange={(e) => setEnvironmentRef(e.target.value)}
              />
            </label>
            <label className="flex flex-col text-xs text-[var(--color-text-dim)]">
              Region
              <input
                type="text"
                className="mt-1 rounded-md border border-[var(--color-border)] bg-[var(--color-bg)] px-3 py-2 text-sm"
                data-testid="install-page-region"
                value={region}
                onChange={(e) => setRegion(e.target.value)}
              />
            </label>
            <label className="flex flex-col text-xs text-[var(--color-text-dim)]">
              Placement mode
              <select
                className="mt-1 rounded-md border border-[var(--color-border)] bg-[var(--color-bg)] px-3 py-2 text-sm"
                data-testid="install-page-placement"
                value={placementMode}
                onChange={(e) => setPlacementMode(e.target.value)}
              >
                <option value="single-region">single-region</option>
                <option value="active-active">active-active</option>
                <option value="active-hotstandby">active-hotstandby</option>
              </select>
            </label>
          </div>

          {/* Auto-form for Blueprint parameters. */}
          {versionQuery.isLoading ? (
            <div className="text-xs text-[var(--color-text-dim)]" data-testid="install-page-form-loading">
              Loading Blueprint parameters…
            </div>
          ) : null}
          {versionQuery.data ? (
            <InstallForm
              blueprint={versionQuery.data}
              onSubmit={handleSubmit}
              onPreview={handlePreview}
            />
          ) : null}

          {installError ? (
            <div
              className="mt-3 rounded-md border border-red-500/40 bg-red-500/10 px-3 py-2 text-xs text-red-400"
              data-testid="install-page-error"
            >
              {installError}
            </div>
          ) : null}
        </div>
      ) : null}

      {/* Preview modal */}
      {previewState ? (
        <div
          role="dialog"
          aria-modal="true"
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4"
          data-testid="install-page-preview-modal"
        >
          <div className="max-h-[80vh] w-full max-w-3xl overflow-auto rounded-lg border border-[var(--color-border)] bg-[var(--color-bg)] p-5">
            <div className="mb-3 flex items-baseline justify-between">
              <h3 className="text-base font-semibold text-[var(--color-text)]">
                Preview — {previewState.blueprint.name}@{previewState.blueprint.version}
              </h3>
              <button
                type="button"
                className="text-xs text-[var(--color-text-dim)] hover:text-[var(--color-text)]"
                data-testid="install-page-preview-close"
                onClick={dismissPreview}
              >
                Close
              </button>
            </div>
            {previewState.warnings.length > 0 ? (
              <ul className="mb-3 list-disc rounded-md border border-yellow-500/40 bg-yellow-500/10 px-4 py-2 pl-6 text-xs text-yellow-300">
                {previewState.warnings.map((w, i) => (
                  <li key={i}>{w}</li>
                ))}
              </ul>
            ) : null}
            {previewState.manifests.map((m) => (
              <div key={m.path} className="mb-3" data-testid={`install-page-preview-manifest-${m.path}`}>
                <div className="text-xs font-mono text-[var(--color-text-dim)]">{m.path}</div>
                <pre className="mt-1 overflow-auto rounded-md border border-[var(--color-border)] bg-[var(--color-bg-elev)] p-3 text-[11px] leading-5 text-[var(--color-text)]">
                  {m.content}
                </pre>
              </div>
            ))}
          </div>
        </div>
      ) : null}

      {/* Status modal */}
      {statusName ? (
        <div
          role="dialog"
          aria-modal="true"
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4"
          data-testid="install-page-status-modal"
        >
          <div className="w-full max-w-md rounded-lg border border-[var(--color-border)] bg-[var(--color-bg)] p-5">
            <h3 className="text-base font-semibold text-[var(--color-text)]">Application installed</h3>
            <p className="mt-1 text-sm text-[var(--color-text-dim)]">
              {statusName} is now reconciling. The application-controller will provision Flux
              HelmReleases for each region; status updates will appear on the Apps page.
            </p>
            <div className="mt-4 flex justify-end">
              <button
                type="button"
                className="rounded-md bg-[var(--color-accent)] px-3 py-1.5 text-xs text-[var(--color-bg)] hover:opacity-90"
                data-testid="install-page-status-close"
                onClick={dismissStatus}
              >
                Open Apps
              </button>
            </div>
          </div>
        </div>
      ) : null}
    </div>
  )
}
