'use client'

import { useEffect, useState } from 'react'
import { FileText, Mail, Send } from 'lucide-react'
import { cmsApi } from '../../../lib/api.js'
import type { BlockPreviewProps } from './index.js'

interface PreviewField {
  key: string
  label: string
  type: string
}

interface PreviewForm {
  name: string
  fields: PreviewField[]
}

/**
 * Canvas preview for the form block. When a form is linked we fetch its real
 * name + fields so the editor sees what will render; otherwise we fall back to
 * a generic skeleton. Network failures degrade to the skeleton rather than
 * breaking the canvas.
 */
export function FormPreview({ data, variant = 'contact' }: BlockPreviewProps) {
  const formId = (data.formId as string) || ''
  const [form, setForm] = useState<PreviewForm | null>(null)
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (!formId) {
      setForm(null)
      return
    }
    let cancelled = false
    setLoading(true)
    cmsApi<{ name?: string; fields?: PreviewField[] }>(`/forms/${encodeURIComponent(formId)}`)
      .then((res) => {
        if (cancelled) return
        if (res.data?.name) {
          setForm({ name: res.data.name, fields: res.data.fields ?? [] })
        } else {
          setForm(null)
        }
      })
      .finally(() => {
        if (!cancelled) setLoading(false)
      })
    return () => {
      cancelled = true
    }
  }, [formId])

  if (!formId) {
    return (
      <div className="border-border bg-muted/30 rounded-md border border-dashed p-6 text-center">
        <FileText size={20} className="text-muted-foreground mx-auto" />
        <p className="text-muted-foreground mt-2 text-sm">No form selected</p>
        <p className="text-muted-foreground/70 text-xs">Pick a form in the block settings</p>
      </div>
    )
  }

  const heading = form?.name ?? (loading ? 'Loading form…' : 'Contact Form')
  const fields = form?.fields ?? []

  if (variant === 'newsletter') {
    return (
      <div className="border-border rounded-md border p-6 text-center">
        <Mail size={24} className="text-muted-foreground mx-auto" />
        <p className="text-foreground mt-3 text-sm font-medium">
          {form?.name ?? 'Newsletter Signup'}
        </p>
        <div className="mx-auto mt-4 flex max-w-xs gap-2">
          <div className="border-border bg-input-background h-9 flex-1 rounded-md border" />
          <div className="bg-primary flex h-9 items-center rounded-md px-3">
            <Send size={14} className="text-primary-foreground" />
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="border-border rounded-md border p-5">
      <div className="flex items-center gap-2">
        <FileText size={16} className="text-muted-foreground" />
        <p className="text-foreground text-sm font-medium">{heading}</p>
      </div>
      <div className="mt-3 flex flex-col gap-2">
        {fields.length > 0 ? (
          fields.slice(0, 5).map((field) => (
            <div key={field.key}>
              <p className="text-muted-foreground mb-1 text-xs">{field.label || field.key}</p>
              <div
                className={`border-border bg-input-background rounded-md border ${
                  field.type === 'textarea' ? 'h-16' : 'h-8'
                }`}
              />
            </div>
          ))
        ) : (
          <>
            <div className="border-border bg-input-background h-8 rounded-md border" />
            <div className="border-border bg-input-background h-8 rounded-md border" />
            <div className="border-border bg-input-background h-20 rounded-md border" />
          </>
        )}
      </div>
      <div className="mt-3">
        <span className="bg-primary text-primary-foreground inline-block rounded-md px-4 py-2 text-sm">
          {variant === 'custom' ? 'Submit' : 'Send Message'}
        </span>
      </div>
    </div>
  )
}
