/**
 * 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">
      <div className="mb-4 flex items-baseline justify-between">
        <h1 className="text-2xl font-semibold text-[var(--color-text)]">Install Blueprint</h1>
        <span className="text-sm text-[var(--color-text-dim)]">
          {catalogQuery.data?.length ?? 0} blueprints visible
        </span>
      </div>

      {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}

      {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}
            </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>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>
  )
}
