'use client'

import { useEffect, useState } from 'react'
import { AlertTriangle, Loader2, Pencil, X } from 'lucide-react'
import { fetchPageForEditor, type EditorPage } from '../../lib/page-editor-service.js'
import { SectionRenderer } from './sections/index.js'

interface PagePreviewProps {
  documentId: string
  onNavigate: (path: string) => void
}

/**
 * Clean, chrome-free render of a page using the SAME section renderers as
 * the editor canvas — so the preview reflects what will actually ship.
 * Only visible sections are rendered (hidden sections are omitted, exactly
 * as the public page would behave).
 */
export function PagePreview({ documentId, onNavigate }: PagePreviewProps) {
  const [page, setPage] = useState<EditorPage | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    let cancelled = false
    setLoading(true)
    fetchPageForEditor(documentId)
      .then((p) => !cancelled && setPage(p))
      .catch((err) => !cancelled && setError(err instanceof Error ? err.message : 'Failed to load'))
      .finally(() => !cancelled && setLoading(false))
    return () => {
      cancelled = true
    }
  }, [documentId])

  if (loading) {
    return (
      <div className="bg-background flex h-full items-center justify-center">
        <Loader2 className="text-muted-foreground h-6 w-6 animate-spin" aria-hidden />
        <span className="sr-only">Loading preview…</span>
      </div>
    )
  }

  if (error || !page) {
    return (
      <div className="bg-background flex h-full items-center justify-center p-6">
        <div className="border-destructive/30 bg-destructive/5 flex max-w-md items-center gap-3 rounded-lg border p-4">
          <AlertTriangle className="text-destructive shrink-0" size={20} aria-hidden />
          <p className="text-foreground text-sm font-medium">{error ?? 'Page not found.'}</p>
        </div>
      </div>
    )
  }

  const visible = page.sections.filter((s) => s.visible)

  return (
    <div className="flex h-full flex-col">
      {/* Slim preview bar — the only chrome; the page itself renders clean.
          This view opens in its own browser tab, so actions are tab-scoped. */}
      <div className="bg-card border-border flex h-12 shrink-0 items-center justify-between border-b px-4">
        <button
          type="button"
          onClick={() => {
            // Opened via the editor's "Preview" (script-opened tab) → close
            // it. Opened by navigating to the URL directly (no opener, so
            // `window.close()` is a no-op) → fall back to the editor so the
            // button is never dead.
            if (window.opener) window.close()
            else onNavigate(`/pages/${documentId}/edit`)
          }}
          className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1.5 text-sm"
          aria-label="Close preview tab"
        >
          <X className="h-4 w-4" aria-hidden />
          Close
        </button>
        <span className="text-muted-foreground text-xs">
          Preview · {page.title || 'Untitled'} {page.path}
        </span>
        <button
          type="button"
          onClick={() => onNavigate(`/pages/${documentId}/edit`)}
          className="bg-primary text-primary-foreground hover:bg-primary/90 inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium"
        >
          <Pencil className="h-3.5 w-3.5" aria-hidden />
          Open editor
        </button>
      </div>

      {/* The canvas is intentionally white regardless of the admin theme:
          it emulates the public page surface, not admin chrome. */}
      <div className="bg-card flex-1 overflow-auto">
        {visible.length === 0 ? (
          <div className="text-muted-foreground flex h-full items-center justify-center text-sm">
            This page has no visible sections yet.
          </div>
        ) : (
          visible.map((section) => <SectionRenderer key={section.id} section={section} />)
        )}
      </div>
    </div>
  )
}
