// src/components/DealDetails/DealComments.tsx
import React, { useEffect, useMemo, useState } from "react"
import { Link } from "react-router-dom"
import { Heart, MessageCircle, MoreHorizontal, Trash2 } from "lucide-react"
import { getComments, postComment, deleteComment } from "../../api/deal/commentDeal"
import { useAuth } from "../../context/AuthContext"
import { timeAgo } from "../../utils/timeAgo"
import type { Comment } from "../../models/comment/Comment"

type DealCommentsProps = {
  dealId: number
  onRequireLogin: () => void
}

type CommentRowProps = {
  c: Comment
  isReply?: boolean

  currentUserId: number | null
  isAuthenticated: boolean
  onRequireLogin: () => void

  deletingId: number | null
  onDelete: (commentId: number) => void

  replyToId: number | null
  setReplyToId: (id: number | null) => void
  replyText: string
  setReplyText: (v: string) => void
  onReplySubmit: (e: React.FormEvent, parentId: number) => void

  repliesByParent: Map<number, Comment[]>
}

function CommentRow({
  c,
  isReply = false,
  currentUserId,
  isAuthenticated,
  onRequireLogin,
  deletingId,
  onDelete,
  replyToId,
  setReplyToId,
  replyText,
  setReplyText,
  onReplySubmit,
  repliesByParent,
}: CommentRowProps) {
  const isMine = currentUserId != null && c.user?.id === currentUserId
  const replies = repliesByParent.get(c.id) ?? []

  const wrapClass = isReply
    ? "mt-4 rounded-2xl border border-white/10 bg-background/60 p-4 relative"
    : "py-5 first:pt-0 last:pb-0"

  return (
    <div className={wrapClass}>
      {isReply && (
        <>
          <span
            aria-hidden
            className="absolute left-0 top-0 h-full w-1 rounded-l-2xl bg-primary/30"
          />
          <div className="mb-2 flex items-center gap-2 pl-2">
            <span className="inline-flex items-center gap-2 rounded-full border border-primary/25 bg-primary/10 px-3 py-1 text-xs font-semibold text-primary">
              Yanıt
            </span>
          </div>
        </>
      )}

      <div className={`flex gap-3 ${isReply ? "pl-2" : ""}`}>
        <Link to={`/user/${c.user.username}`} className="shrink-0">
          <img
            src={
              c.user.avatarUrl ||
              `${import.meta.env.BASE_URL}placeholders/placeholder-profile.png`
            }
            alt={c.user.username}
            className={`${isReply ? "w-12 h-12" : "w-14 h-14"} rounded-full object-cover border border-white/10`}
          />
        </Link>

        <div className="min-w-0 flex-1">
          <div className="flex items-center justify-between gap-3">
            <div className="min-w-0 flex items-center gap-2">
              <Link
                to={`/user/${c.user.username}`}
                className="text-base font-semibold text-text hover:underline truncate"
              >
                {c.user.username}
              </Link>
              <span className="text-xs text-text-muted">{timeAgo(c.createdAt)}</span>
            </div>

            {isMine ? (
              <button
                type="button"
                onClick={() => onDelete(c.id)}
                disabled={deletingId === c.id}
                className="inline-flex items-center gap-2 rounded-lg px-3 py-2 bg-background border border-white/10 text-text-muted hover:text-red-400 hover:border-white/20 transition disabled:opacity-60 disabled:cursor-not-allowed"
                aria-label="Yorumu sil"
                title="Sil"
              >
                <Trash2 className="w-4 h-4" />
                <span className="text-xs font-semibold">
                  {deletingId === c.id ? "Siliniyor..." : "Sil"}
                </span>
              </button>
            ) : (
              <button
                type="button"
                className="inline-flex items-center justify-center rounded-lg p-2 bg-background border border-white/10 text-text-muted hover:text-text hover:border-white/20 transition"
                aria-label="Yorum seçenekleri"
              >
                <MoreHorizontal className="w-4 h-4" />
              </button>
            )}
          </div>

          <p className="mt-2 text-base text-text leading-relaxed whitespace-pre-line">
            {c.text}
          </p>

          <div className="mt-3 flex items-center gap-2">
            <button
              type="button"
              className="inline-flex items-center gap-2 rounded-lg px-3 py-2 text-xs font-semibold bg-background border border-white/10 text-text-muted hover:text-primary hover:border-white/20 transition"
            >
              <Heart className="w-4 h-4" />
              <span>25</span>
            </button>

            <button
              type="button"
              onClick={() => {
                if (!isAuthenticated) return onRequireLogin()
                setReplyToId(c.id)
                setReplyText("")
              }}
              className="inline-flex items-center gap-2 rounded-lg px-3 py-2 text-xs font-semibold bg-background border border-white/10 text-text-muted hover:text-primary hover:border-white/20 transition"
            >
              <MessageCircle className="w-4 h-4" />
              <span>Yanıtla</span>
            </button>
          </div>

          {replyToId === c.id && (
            <form
              onSubmit={(e) => onReplySubmit(e, c.id)}
              className="mt-3 flex items-center gap-3"
            >
              <input
                type="text"
                value={replyText}
                onChange={(e) => setReplyText(e.target.value)}
                placeholder="Yanıt yaz..."
                autoFocus
                className="flex-1 rounded-xl border border-white/10 bg-background px-4 py-3 text-sm text-text placeholder:text-text-muted/70 outline-none focus:ring-2 focus:ring-primary/40"
              />
              <button
                type="submit"
                className="shrink-0 rounded-xl px-4 py-3 text-sm font-semibold bg-primary text-black hover:bg-primary-hover transition disabled:opacity-60 disabled:cursor-not-allowed"
              >
                Gönder
              </button>
              <button
                type="button"
                onClick={() => {
                  setReplyToId(null)
                  setReplyText("")
                }}
                className="shrink-0 rounded-xl px-4 py-3 text-sm font-semibold bg-background border border-white/10 text-text-muted hover:border-white/20 transition"
              >
                İptal
              </button>
            </form>
          )}

          {replies.length > 0 && (
            <div className="mt-4">
              <div className="pl-6 border-l border-primary/20">
                {replies.map((r) => (
                  <CommentRow
                    key={r.id}
                    c={r}
                    isReply
                    currentUserId={currentUserId}
                    isAuthenticated={isAuthenticated}
                    onRequireLogin={onRequireLogin}
                    deletingId={deletingId}
                    onDelete={onDelete}
                    replyToId={replyToId}
                    setReplyToId={setReplyToId}
                    replyText={replyText}
                    setReplyText={setReplyText}
                    onReplySubmit={onReplySubmit}
                    repliesByParent={repliesByParent}
                  />
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

export default function DealComments({ dealId, onRequireLogin }: DealCommentsProps) {
  const [comments, setComments] = useState<Comment[]>([])
  const [newComment, setNewComment] = useState("")
  const [loading, setLoading] = useState(false)
  const [deletingId, setDeletingId] = useState<number | null>(null)

  const [replyToId, setReplyToId] = useState<number | null>(null)
  const [replyText, setReplyText] = useState("")

  const auth = useAuth()
  const { isAuthenticated } = auth
  const currentUserId = (auth as any)?.user?.id ?? (auth as any)?.userId ?? null

  useEffect(() => {
    async function loadComments() {
      try {
        const data = await getComments(dealId)
        setComments(data)
      } catch (err) {
        console.error("Yorumlar alınamadı:", err)
      }
    }
    loadComments()
  }, [dealId])

  const { roots, repliesByParent } = useMemo(() => {
    const roots: Comment[] = []
    const map = new Map<number, Comment[]>()

    for (const c of comments) {
      const pid = (c as any).parentId ?? null
      if (pid == null) roots.push(c)
      else {
        const arr = map.get(pid) ?? []
        arr.push(c)
        map.set(pid, arr)
      }
    }

    roots.sort((a, b) => Number(new Date(b.createdAt)) - Number(new Date(a.createdAt)))
    for (const [k, arr] of map.entries()) {
      arr.sort((a, b) => Number(new Date(b.createdAt)) - Number(new Date(a.createdAt)))
      map.set(k, arr)
    }

    return { roots, repliesByParent: map }
  }, [comments])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!newComment.trim()) return
    if (!isAuthenticated) return onRequireLogin()

    setLoading(true)
    try {
      const added = await postComment(dealId, newComment, null)
      setComments((prev) => [added, ...prev])
      setNewComment("")
    } catch (err: any) {
      console.error(err)
      alert(err.message || "Sunucu hatası")
    } finally {
      setLoading(false)
    }
  }

  const handleReplySubmit = async (e: React.FormEvent, parentId: number) => {
    e.preventDefault()
    if (!replyText.trim()) return
    if (!isAuthenticated) return onRequireLogin()

    setLoading(true)
    try {
      const added = await postComment(dealId, replyText, parentId)
      setComments((prev) => [added, ...prev])
      setReplyText("")
      setReplyToId(null)
    } catch (err: any) {
      console.error(err)
      alert(err.message || "Sunucu hatası")
    } finally {
      setLoading(false)
    }
  }

  const handleDelete = async (commentId: number) => {
    if (!isAuthenticated) return onRequireLogin()
    const ok = window.confirm("Yorum silinsin mi?")
    if (!ok) return

    setDeletingId(commentId)
    try {
      await deleteComment(commentId)
      setComments((prev) => prev.filter((c) => c.id !== commentId))
    } catch (err: any) {
      console.error(err)
      alert(err.message || "Yorum silinemedi")
    } finally {
      setDeletingId(null)
    }
  }

  return (
    <div className="rounded-3xl bg-surface border border-white/10 p-5 flex flex-col">
      <div className="flex items-center justify-between gap-3">
        <h2 className="text-lg font-semibold text-text">Yorumlar</h2>
        <span className="text-xs text-text-muted bg-background border border-white/10 rounded-full px-3 py-1">
          {comments.length}
        </span>
      </div>

      <div className="mt-4 flex-1 lg:max-h-[calc(100vh-280px)] lg:overflow-y-auto pr-2">
        {roots.length > 0 ? (
          <div className="divide-y divide-white/10">
            {roots.map((c) => (
              <CommentRow
                key={c.id}
                c={c}
                currentUserId={currentUserId}
                isAuthenticated={isAuthenticated}
                onRequireLogin={onRequireLogin}
                deletingId={deletingId}
                onDelete={handleDelete}
                replyToId={replyToId}
                setReplyToId={setReplyToId}
                replyText={replyText}
                setReplyText={setReplyText}
                onReplySubmit={handleReplySubmit}
                repliesByParent={repliesByParent}
              />
            ))}
          </div>
        ) : (
          <div className="rounded-2xl bg-background border border-white/10 p-4 text-center">
            <div className="text-sm font-semibold text-text">Henüz yorum yok</div>
            <div className="text-xs text-text-muted mt-1">İlk yorumu sen yazabilirsin.</div>
          </div>
        )}
      </div>

      <div className="mt-5 pt-5 border-t border-white/10">
        {isAuthenticated ? (
          <form onSubmit={handleSubmit} className="flex items-center gap-3">
            <input
              type="text"
              value={newComment}
              onChange={(e) => setNewComment(e.target.value)}
              placeholder="Yorum ekle..."
              className="flex-1 rounded-xl border border-white/10 bg-background px-4 py-3 text-sm text-text placeholder:text-text-muted/70 outline-none focus:ring-2 focus:ring-primary/40"
              disabled={loading}
            />
            <button
              type="submit"
              disabled={loading}
              className="shrink-0 rounded-xl px-5 py-3 text-sm font-semibold bg-primary text-black hover:bg-primary-hover transition disabled:opacity-60 disabled:cursor-not-allowed"
            >
              {loading ? "..." : "Gönder"}
            </button>
          </form>
        ) : (
          <button
            type="button"
            onClick={onRequireLogin}
            className="w-full rounded-xl border border-white/10 bg-background px-4 py-3 text-sm font-semibold text-primary hover:border-white/20 transition"
          >
            Yorum yazmak için giriş yap veya kayıt ol
          </button>
        )}
      </div>
    </div>
  )
}
