import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { fetchComments, postComment, deleteComment } from '../api/endpoints'
import { useAuth } from '../context/AuthContext'
import { useToast } from '../context/ToastContext'
import { timeAgo } from '../lib/format'
import { Trash } from './icons'

export default function CommentSection({ slug }) {
  const { user, isAuthenticated } = useAuth()
  const toast = useToast()
  const [comments, setComments] = useState([])
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(false)
  const [body, setBody] = useState('')
  const [busy, setBusy] = useState(false)
  const [loading, setLoading] = useState(true)

  const load = async (p = 1) => {
    setLoading(true)
    try {
      const res = await fetchComments(slug, p)
      setComments((prev) => (p === 1 ? res.data : [...prev, ...res.data]))
      setTotal(res.meta?.total ?? res.data.length)
      setHasMore((res.meta?.current_page ?? p) < (res.meta?.last_page ?? p))
      setPage(p)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    load(1)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [slug])

  const submit = async (e) => {
    e.preventDefault()
    if (!body.trim()) return
    setBusy(true)
    try {
      const c = await postComment(slug, body.trim())
      setComments((prev) => [c, ...prev])
      setTotal((t) => t + 1)
      setBody('')
    } catch {
      toast.error('Could not post comment')
    } finally {
      setBusy(false)
    }
  }

  const remove = async (id) => {
    try {
      await deleteComment(id)
      setComments((prev) => prev.filter((c) => c.id !== id))
      setTotal((t) => Math.max(0, t - 1))
    } catch {
      toast.error('Could not delete')
    }
  }

  return (
    <section className="mt-6">
      <h2 className="mb-4 text-lg font-bold">{total} Comments</h2>

      {isAuthenticated ? (
        <form onSubmit={submit} className="mb-6 flex gap-3">
          <div className="flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded-full bg-[var(--brand)] text-sm font-bold text-white">
            {user.avatar ? <img src={user.avatar} alt="" className="h-full w-full object-cover" /> : user.name?.[0]}
          </div>
          <div className="flex-1">
            <textarea
              value={body}
              onChange={(e) => setBody(e.target.value)}
              placeholder="Add a comment…"
              rows={2}
              className="w-full resize-none rounded-xl border border-gray-200 bg-white px-3 py-2 outline-none focus:border-[var(--brand)] focus:ring-2 focus:ring-[var(--brand)]/30 dark:border-gray-700 dark:bg-gray-800"
            />
            <div className="mt-2 flex justify-end">
              <button
                disabled={busy || !body.trim()}
                className="rounded-lg bg-[var(--brand)] px-4 py-1.5 text-sm font-semibold text-white disabled:opacity-50"
              >
                Comment
              </button>
            </div>
          </div>
        </form>
      ) : (
        <p className="mb-6 rounded-xl bg-gray-100 px-4 py-3 text-sm text-gray-600 dark:bg-gray-800 dark:text-gray-300">
          <Link to="/login" className="font-semibold text-[var(--brand)]">
            Log in
          </Link>{' '}
          to join the conversation.
        </p>
      )}

      <div className="space-y-4">
        {comments.map((c) => (
          <div key={c.id} className="flex gap-3">
            <div className="flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded-full bg-gray-300 text-sm font-bold text-white dark:bg-gray-700">
              {c.user?.avatar ? (
                <img src={c.user.avatar} alt="" className="h-full w-full object-cover" />
              ) : (
                c.user?.name?.[0]?.toUpperCase()
              )}
            </div>
            <div className="flex-1">
              <div className="flex items-center gap-2">
                <span className="text-sm font-semibold">{c.user?.name}</span>
                {c.user?.is_admin && (
                  <span className="rounded bg-[var(--brand)]/10 px-1.5 py-0.5 text-[10px] font-bold text-[var(--brand)]">
                    ADMIN
                  </span>
                )}
                <span className="text-xs text-gray-400">{timeAgo(c.created_at)}</span>
                {(user?.id === c.user?.id || user?.is_admin) && (
                  <button
                    onClick={() => remove(c.id)}
                    className="ml-auto text-gray-400 hover:text-rose-500"
                    title="Delete"
                  >
                    <Trash width={15} height={15} />
                  </button>
                )}
              </div>
              <p className="mt-0.5 whitespace-pre-wrap text-sm text-gray-700 dark:text-gray-200">
                {c.body}
              </p>
            </div>
          </div>
        ))}

        {loading && <p className="text-sm text-gray-400">Loading comments…</p>}
        {!loading && comments.length === 0 && (
          <p className="text-sm text-gray-400">No comments yet. Be the first!</p>
        )}
        {hasMore && (
          <button
            onClick={() => load(page + 1)}
            className="text-sm font-semibold text-[var(--brand)] hover:underline"
          >
            Load more comments
          </button>
        )}
      </div>
    </section>
  )
}
