'use client'

import { useEffect, useState } from 'react'
import { AlertTriangle, Loader2, Pencil, X } from 'lucide-react'
import {
  fetchPostForEditor,
  fetchTemplateForEditor,
  type EditorPost,
  type PostHeaderConfig,
} from '../../lib/post-editor-service.js'
import { defaultPostHeader } from '@actuate-media/cms-core/page-sections'
import { SectionRenderer, type PostRenderContext } from '../page-editor/sections/index.js'
import { PostHeader } from './PostHeader.js'

interface PostPreviewProps {
  postType: string
  documentId: string
  session?: any
  onNavigate: (path: string) => void
}

/**
 * Chrome-free render of a post using the same header + section renderers as
 * the editor canvas, so the preview reflects what ships. Only visible
 * sections render (hidden ones are omitted, like the public page).
 */
export function PostPreview({ postType, documentId, session, onNavigate }: PostPreviewProps) {
  const [post, setPost] = useState<EditorPost | null>(null)
  const [header, setHeader] = useState<PostHeaderConfig>(defaultPostHeader())
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    let cancelled = false
    setLoading(true)
    fetchTemplateForEditor(postType)
      .then((t) => !cancelled && setHeader(t.header))
      .catch(() => {
        /* default header */
      })
    fetchPostForEditor(postType, documentId)
      .then((p) => !cancelled && setPost(p))
      .catch((err) => !cancelled && setError(err instanceof Error ? err.message : 'Failed to load'))
      .finally(() => !cancelled && setLoading(false))
    return () => {
      cancelled = true
    }
  }, [postType, 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 || !post) {
    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 ?? 'Post not found.'}</p>
        </div>
      </div>
    )
  }

  const context: PostRenderContext = {
    title: post.title,
    excerpt: post.excerpt,
    body: post.body,
    featuredImageUrl: post.featuredImage,
    publishDate: post.publishDate ?? post.updatedAt ?? null,
    category: post.category,
    author: { name: session?.user?.name || session?.user?.email },
  }
  const visible = post.sections.filter((s) => s.visible)

  // `window.close()` only works for tabs JS opened (the "View preview" action
  // opens this view via window.open). When the user reached it through in-app
  // navigation there is no opener, so close() is a silent no-op — fall back to
  // the editor after a tick so the Close button always does something.
  const handleClose = () => {
    window.close()
    setTimeout(() => {
      onNavigate(`/posts/${postType}/${documentId}/edit`)
    }, 120)
  }

  return (
    <div className="flex h-full flex-col">
      {/* Slim preview bar. 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={handleClose}
          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 · {post.title || 'Untitled'}</span>
        <button
          type="button"
          onClick={() => onNavigate(`/posts/${postType}/${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>

      <div className="bg-card flex-1 overflow-auto">
        <PostHeader config={header} context={context} />
        {visible.map((section) => (
          <SectionRenderer key={section.id} section={section} context={context} />
        ))}
      </div>
    </div>
  )
}
