import React, { useState } from 'react'

export default function CommentForm({ placeholder = 'Write a comment…', submitLabel = 'Post', onSubmit, onCancel, compact = false }) {
  const [content, setContent] = useState('')
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState('')

  const handleSubmit = async (event) => {
    event.preventDefault()
    const trimmed = content.trim()
    if (!trimmed || busy) return

    setBusy(true)
    setError('')
    try {
      await onSubmit?.(trimmed)
      setContent('')
    } catch (submitError) {
      setError(submitError?.message || 'Unable to post comment.')
    } finally {
      setBusy(false)
    }
  }

  return (
    <form className="space-y-3" onSubmit={handleSubmit}>
      <textarea
        value={content}
        onChange={(event) => setContent(event.target.value)}
        rows={compact ? 3 : 4}
        maxLength={10000}
        placeholder={placeholder}
        className="w-full rounded-2xl border border-white/[0.08] bg-white/[0.04] px-4 py-3 text-sm text-white placeholder-white/35 outline-none transition focus:border-sky-400/40 focus:bg-white/[0.06]"
      />

      {error ? <p className="text-sm text-rose-300">{error}</p> : null}

      <div className="flex items-center justify-between gap-3">
        <span className="text-xs text-white/35">{content.trim().length}/10000</span>
        <div className="flex items-center gap-2">
          {onCancel ? (
            <button
              type="button"
              onClick={onCancel}
              className="rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-sm font-medium text-white/70 transition hover:bg-white/[0.08] hover:text-white"
            >
              Cancel
            </button>
          ) : null}
          <button
            type="submit"
            disabled={busy || content.trim().length === 0}
            className="rounded-full bg-sky-500 px-4 py-2 text-sm font-semibold text-white transition hover:bg-sky-400 disabled:cursor-not-allowed disabled:opacity-60"
          >
            {busy ? 'Posting…' : submitLabel}
          </button>
        </div>
      </div>
    </form>
  )
}