import { useCallback, useState } from 'react'
import type { ContentEntry, ContentInput, ContentVisibility } from '@platform-modules/content'
import { RichTextEditor } from '@platform-modules/ui-editor'
import type { ContentClient } from './client.js'

export interface ContentEditorFormProps {
  client: ContentClient
  /** Edit an existing entry, or `null` for a new one. */
  entry: ContentEntry | null
  onSaved?: (entry: ContentEntry) => void
  className?: string
}

const VISIBILITY_OPTIONS: ContentVisibility[] = ['public', 'private', 'members']

export function ContentEditorForm({ client, entry, onSaved, className }: ContentEditorFormProps) {
  const [title, setTitle] = useState(entry?.title ?? '')
  const [slug, setSlug] = useState(entry?.slug ?? '')
  const [type, setType] = useState(entry?.type ?? '')
  const [visibility, setVisibility] = useState<ContentVisibility>(entry?.visibility ?? 'public')
  const [body, setBody] = useState(entry?.body ?? '')
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<Error | null>(null)

  const handleSave = useCallback(async () => {
    setSaving(true)
    setError(null)
    const input: ContentInput = {
      ...(entry?.id ? { id: entry.id } : {}),
      slug,
      type,
      title,
      body,
      visibility,
    }
    try {
      const saved = await client.put(input)
      onSaved?.(saved)
    } catch (e: unknown) {
      setError(e instanceof Error ? e : new Error(String(e)))
    } finally {
      setSaving(false)
    }
  }, [body, client, entry?.id, onSaved, slug, title, type, visibility])

  return (
    <form
      className={className}
      onSubmit={(e) => {
        e.preventDefault()
        void handleSave()
      }}
    >
      <p>
        <label htmlFor="content-title">
          Title
          <input
            id="content-title"
            type="text"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
          />
        </label>
      </p>
      <p>
        <label htmlFor="content-slug">
          Slug
          <input id="content-slug" type="text" value={slug} onChange={(e) => setSlug(e.target.value)} />
        </label>
      </p>
      <p>
        <label htmlFor="content-type">
          Type
          <input id="content-type" type="text" value={type} onChange={(e) => setType(e.target.value)} />
        </label>
      </p>
      <p>
        <label htmlFor="content-visibility">
          Visibility
          <select
            id="content-visibility"
            value={visibility}
            onChange={(e) => setVisibility(e.target.value as ContentVisibility)}
          >
            {VISIBILITY_OPTIONS.map((v) => (
              <option key={v} value={v}>
                {v}
              </option>
            ))}
          </select>
        </label>
      </p>
      <div>
        <label>
          Body
          <RichTextEditor value={body} onChange={setBody} aria-label="Content body" />
        </label>
      </div>
      {error ? <p role="alert">{error.message}</p> : null}
      <button type="submit" disabled={saving}>
        {saving ? 'Saving…' : 'Save'}
      </button>
    </form>
  )
}
