'use client'

/**
 * Embed tab of the Form Schema drawer. Shows the live public schema/submission
 * endpoints and a ready-to-paste `<ActuateForm>` snippet, and lets the editor
 * restrict which origins may host the embedded form. Endpoints are derived from
 * the form slug and match the public API mounted at `/api/cms`.
 */
import { Check, Copy } from 'lucide-react'
import { useEffect, useState } from 'react'
import { toast } from 'sonner'
import {
  fetchEmbedSettings,
  updateEmbedSettings,
  type FormEmbedSettings,
  type FormStatus,
} from '../../lib/forms-service.js'
import { FormsErrorState, FormsLoading, btnSecondary } from './primitives.js'

function siteOrigin(): string {
  if (typeof window !== 'undefined') return window.location.origin
  return 'https://your-site.com'
}

export function EmbedPanel({
  formId,
  slug,
  status,
}: {
  formId: string
  slug: string
  status: FormStatus
}) {
  const [settings, setSettings] = useState<FormEmbedSettings | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [domains, setDomains] = useState('')
  const [saving, setSaving] = useState(false)

  useEffect(() => {
    let active = true
    setLoading(true)
    setError(null)
    fetchEmbedSettings(formId)
      .then((s) => {
        if (!active) return
        setSettings(s)
        setDomains((s.allowedDomains ?? []).join('\n'))
      })
      .catch((e: unknown) => {
        if (active) setError(e instanceof Error ? e.message : 'Failed to load embed settings')
      })
      .finally(() => {
        if (active) setLoading(false)
      })
    return () => {
      active = false
    }
  }, [formId])

  const origin = siteOrigin()
  const schemaUrl = `${origin}/api/cms/public/forms/${slug}`
  const submitUrl = `${origin}/api/cms/public/forms/${slug}/submit`
  const componentSnippet = `import { ActuateForm } from '@actuate-media/sections-react'\n\n<ActuateForm slug="${slug}" />`

  async function saveDomains() {
    setSaving(true)
    const list = domains
      .split('\n')
      .map((d) => d.trim())
      .filter(Boolean)
    const res = await updateEmbedSettings(formId, { allowedDomains: list })
    setSaving(false)
    if (res.error) {
      toast.error(res.error)
      return
    }
    if (res.data) setSettings(res.data)
    toast.success('Embed settings saved.')
  }

  if (loading) return <FormsLoading label="Loading embed settings…" />
  if (error) return <FormsErrorState message={error} />

  return (
    <div className="space-y-5">
      {status !== 'active' && (
        <p className="border-warning/30 bg-warning/10 text-warning rounded-md border px-3 py-2 text-sm">
          This form is <span className="font-medium">{status}</span> and won&apos;t accept public
          submissions until it&apos;s set to Active.
        </p>
      )}

      <CopyField label="React component" value={componentSnippet} multiline />
      <p className="text-muted-foreground -mt-2 text-xs">
        Renders, validates, and submits this form (with spam protection) using{' '}
        <span className="font-mono">@actuate-media/sections-react</span>. Or add a{' '}
        <span className="font-medium">Form</span> section to any page and set its slug to{' '}
        <span className="font-mono">{slug}</span>.
      </p>

      <CopyField label="Schema endpoint (GET)" value={schemaUrl} />
      <CopyField label="Submission endpoint (POST)" value={submitUrl} />

      <div>
        <label className="text-foreground mb-1 block text-sm font-medium">
          Allowed domains
          <span className="text-muted-foreground ml-1 font-normal">
            (one per line — leave empty to allow any)
          </span>
        </label>
        <textarea
          rows={3}
          value={domains}
          onChange={(e) => setDomains(e.target.value)}
          placeholder="example.com"
          className="border-border bg-input-background text-foreground focus-visible:ring-ring w-full rounded-md border px-2.5 py-1.5 text-sm focus-visible:ring-2 focus-visible:outline-none"
        />
        <div className="mt-2 flex justify-end">
          <button className={btnSecondary} onClick={saveDomains} disabled={saving}>
            {saving ? 'Saving…' : 'Save domains'}
          </button>
        </div>
      </div>
      {settings === null && null}
    </div>
  )
}

function CopyField({
  label,
  value,
  multiline = false,
}: {
  label: string
  value: string
  multiline?: boolean
}) {
  const [copied, setCopied] = useState(false)

  async function copy() {
    try {
      await navigator.clipboard.writeText(value)
      setCopied(true)
      setTimeout(() => setCopied(false), 1500)
    } catch {
      toast.error('Copy failed — your browser blocked clipboard access.')
    }
  }

  return (
    <div>
      <div className="mb-1 flex items-center justify-between">
        <span className="text-foreground text-sm font-medium">{label}</span>
        <button
          type="button"
          onClick={copy}
          className="text-muted-foreground hover:text-foreground focus-visible:ring-ring inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs font-medium focus-visible:ring-2 focus-visible:outline-none"
          aria-label={`Copy ${label}`}
        >
          {copied ? (
            <Check className="h-3.5 w-3.5" aria-hidden />
          ) : (
            <Copy className="h-3.5 w-3.5" aria-hidden />
          )}
          {copied ? 'Copied' : 'Copy'}
        </button>
      </div>
      <pre
        className={`border-border bg-muted text-foreground overflow-x-auto rounded-md border px-2.5 py-2 font-mono text-xs ${multiline ? 'whitespace-pre-wrap' : 'whitespace-nowrap'}`}
      >
        {value}
      </pre>
    </div>
  )
}
