import React, { useState, useCallback } from 'react'
import Breadcrumbs from '../../components/forum/Breadcrumbs'
import Button from '../../components/ui/Button'
import RichTextEditor from '../../components/forum/RichTextEditor'

export default function ForumEditPost({ post, thread, csrfToken, errors = {} }) {
  const [content, setContent] = useState(post?.content ?? '')
  const [submitting, setSubmitting] = useState(false)

  const breadcrumbs = [
    { label: 'Home', href: '/' },
    { label: 'Forum', href: '/forum' },
    { label: thread?.title ?? 'Thread', href: thread?.id ? `/forum/thread/${thread.id}-${thread.slug ?? ''}` : '/forum' },
    { label: 'Edit post' },
  ]

  const handleSubmit = useCallback((e) => {
    if (submitting) return
    setSubmitting(true)
    // Let the form submit normally for PRG
  }, [submitting])

  return (
    <div className="px-4 pt-10 pb-20 sm:px-6 lg:px-8 max-w-3xl mx-auto">
      <Breadcrumbs items={breadcrumbs} />

      {/* Header */}
      <div className="mt-5 mb-6">
        <p className="text-xs font-semibold uppercase tracking-widest text-white/30 mb-1">Edit</p>
        <h1 className="text-2xl font-bold text-white leading-tight">Edit post</h1>
      </div>

      {/* Form */}
      <form
        method="POST"
        action={`/forum/post/${post?.id}`}
        onSubmit={handleSubmit}
        className="space-y-5 rounded-2xl border border-white/[0.06] bg-nova-800/50 p-6 backdrop-blur"
      >
        <input type="hidden" name="_token" value={csrfToken} />
        <input type="hidden" name="_method" value="PUT" />

        {/* Rich text editor */}
        <div>
          <label className="mb-1.5 block text-sm font-medium text-white/85">
            Content
          </label>
          <RichTextEditor
            content={content}
            onChange={setContent}
            placeholder="Edit your post…"
            error={errors.content}
            minHeight={14}
            autofocus={false}
          />
          <input type="hidden" name="content" value={content} />
        </div>

        {/* Actions */}
        <div className="flex items-center justify-between pt-2">
          <a
            href={thread?.id ? `/forum/thread/${thread.id}-${thread.slug ?? ''}` : '/forum'}
            className="text-sm text-zinc-500 hover:text-zinc-300 transition-colors"
          >
            ← Cancel
          </a>
          <Button type="submit" variant="primary" size="md" loading={submitting}>
            Save changes
          </Button>
        </div>
      </form>
    </div>
  )
}
