import React, { useEffect, useState } from "react"
import { Link } from "react-router-dom"
import { getComments, postComment } from "../../api/deal/commentDeal"
import { useAuth } from "../../context/AuthContext"
import { timeAgo } from "../../utils/timeAgo"
import type { Comment } from "../../models/deal/DealComment"

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

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

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

  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)
      setComments((prev) => [added, ...prev])
      setNewComment("")
    } catch (err: any) {
      console.error(err)
      alert(err.message || "Sunucu hatası")
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="bg-surface/50 rounded-xl p-6 border border-border/40">
      <h2 className="text-lg font-semibold mb-6">Yorumlar</h2>

      <div className="space-y-6 mb-6">
        {comments.length > 0 ? (
          comments.map((c) => (
            <div
              key={c.id}
              className="flex gap-3 border-b border-border/30 pb-5 last:border-none"
            >
              <Link to={`/user/${c.user.username}`}>
                <img
                  src={c.user.avatarUrl || `${import.meta.env.BASE_URL}placeholders/placeholder-profile.png`}
                  alt={c.user.username}
                  className="w-10 h-10 rounded-full object-cover"
                />
              </Link>

              <div className="flex-1">
                <div className="flex justify-between items-center">
                  <div className="flex items-center gap-2">
                    <Link
                      to={`/user/${c.user.username}`}
                      className="font-medium text-sm hover:underline"
                    >
                      {c.user.username}
                    </Link>
                    <span className="text-xs text-muted-foreground">
                      {timeAgo(c.createdAt)}
                    </span>
                  </div>
                </div>

                <p className="mt-1 text-sm leading-relaxed">{c.text}</p>

                <div className="flex items-center gap-5 mt-2 text-xs text-muted-foreground">
                  <button className="flex items-center gap-1 hover:text-primary transition">
                    <span>👍</span> <span>25</span>
                  </button>
                  <button className="flex items-center gap-1 hover:text-primary transition">
                    <span>💬</span> <span>Yanıtla</span>
                  </button>
                  <button className="hover:text-primary transition">•••</button>
                </div>
              </div>
            </div>
          ))
        ) : (
          <p className="text-sm text-muted-foreground text-center py-4">
            Henüz yorum yok.
          </p>
        )}
      </div>

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