import { useState, useEffect } from "react"
import { useNavigate } from "react-router-dom"
import { voteDeal } from "../../api/deal/voteDeal"
import { useAuth } from "../../hooks/useAuth"

type DealCardProps = {
  id: number
  image: string
  title: string
  price: string
  store: string
  postedBy: string
  score: number
  comments: number
  postedAgo: string
  onRequireLogin: () => void // yeni prop
}

export default function DealCardMain({
  id,
  image,
  title,
  price,
  store,
  postedBy,
  score,
  comments,
  postedAgo,
  onRequireLogin,
}: DealCardProps) {
  
  const [currentScore, setCurrentScore] = useState<number>(score)
  const [voting, setVoting] = useState(false)
  const navigate = useNavigate()
  const auth = useAuth()   // her render'da güncel context

  useEffect(() => {
    setCurrentScore(score)
  }, [score])

 const handleVote = async (e: React.MouseEvent, type: "UP" | "DOWN") => {
    e.stopPropagation()

    // Context’ten anlık token kontrolü
    const { token, isAuthenticated } = auth
    if (!isAuthenticated || !token) {
      onRequireLogin()
      return
    }

    setVoting(true)
    try {
      const data = await voteDeal( id, type)
      if (typeof data.score === "number") setCurrentScore(data.score)
      else alert(data.error || "Oy gönderilemedi")
    } catch {
      alert("Sunucu hatası")
    } finally {
      setVoting(false)
    }
  }
  const handleCardClick = () => {
    navigate(`/deal/${id}`)
  }

  return (
    <div
      onClick={handleCardClick}
      className="flex bg-surface p-4 rounded-xl hover:shadow-md transition mb-5 cursor-pointer"
    >
      <div className="w-42 h-42 flex-shrink-0">
        <img
          src={image}
          alt={title}
          className="w-full h-full rounded-md object-scale-down"
        />
      </div>

      <div className="flex flex-col justify-between flex-1 ml-4">
        <div>
          <div className="flex justify-between items-center text-l text-text-muted">
            <span className="flex items-center gap-2">
              <button
                disabled={voting}
                onClick={(e) => handleVote(e, "UP")}
                className="text-green-600 font-bold text-lg"
              >
                ▲
              </button>
              <span>{currentScore ?? 0}°</span>
              <button
                disabled={voting}
                onClick={(e) => handleVote(e, "DOWN")}
                className="text-red-600 font-bold text-lg"
              >
                ▼
              </button>
            </span>
            <span>{postedAgo}</span>
          </div>

          <h2 className="text-xl font-semibold text-text mt-1 hover:text-primary">
            {title}
          </h2>

          <div className="flex items-center gap-2 mt-1">
            <span className="text-primary font-bold text-xl">{price}</span>
            <span className="text-sm text-text-muted">{store}</span>
          </div>

          <p className="text-sm text-text-muted mt-1 line-clamp-2">
            {postedBy} tarafından paylaşıldı.
          </p>
        </div>

        <div className="flex justify-between items-center mt-3">
          <div className="flex gap-4 text-sm text-text-muted">
            <span>💬 {comments}</span>
            <span>🔗 Paylaş</span>
          </div>
          <button
            onClick={(e) => e.stopPropagation()}
            className="bg-primary text-white px-4 py-2 rounded-md hover:bg-primary/90"
          >
            Fırsatı kap
          </button>
        </div>
      </div>
    </div>
  )
}
