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

type DealCardProps = {
  id: number
  image: string
  title: string
  price: string
  store: string
  postedBy: string
  score: number
  comments: number
  postedAgo: string
  myVote: 1 | 0 | -1
  onRequireLogin: () => void
}

export default function DealCardMain({
  id,
  image,
  title,
  price,
  store,
  postedBy,
  score,
  comments,
  postedAgo,
  myVote,
  onRequireLogin,
}: DealCardProps) {
  const [currentScore, setCurrentScore] = useState<number>(score)
  const [currentVote, setCurrentVote] = useState<1 | 0 | -1>(myVote)
  const [voting, setVoting] = useState(false)

  const navigate = useNavigate()
  const auth = useAuth()

  useEffect(() => setCurrentScore(score), [score])
  useEffect(() => setCurrentVote(myVote), [myVote])

  const handleVote = async (e: React.MouseEvent, nextVote: 1 | 0 | -1) => {
    e.stopPropagation()

    const { token, isAuthenticated } = auth
    if (!isAuthenticated || !token) {
      onRequireLogin()
      return
    }

    setVoting(true)

    const prevVote = currentVote
    const prevScore = currentScore

    const delta = nextVote - prevVote
    setCurrentVote(nextVote)
    setCurrentScore(prevScore + delta)

    try {
      const data = await voteDeal(id, nextVote)
      if (typeof data.score === "number") {
        setCurrentScore(data.score)
      } else {
        setCurrentVote(prevVote)
        setCurrentScore(prevScore)
        alert(data.error || "Oy gönderilemedi")
      }
    } catch {
      setCurrentVote(prevVote)
      setCurrentScore(prevScore)
      alert("Sunucu hatası")
    } finally {
      setVoting(false)
    }
  }

  const handleUp = (e: React.MouseEvent) => {
    const next: 1 | 0 | -1 = currentVote === 1 ? 0 : 1
    return handleVote(e, next)
  }

  const handleDown = (e: React.MouseEvent) => {
    const next: 1 | 0 | -1 = currentVote === -1 ? 0 : -1
    return handleVote(e, next)
  }

  const handleCardClick = () => navigate(`/deal/${id}`)

  return (
    <div
      onClick={handleCardClick}
      className="flex gap-4 bg-surface p-4 rounded-2xl border border-white/10 hover:border-white/20 hover:shadow-md transition mb-5 cursor-pointer"
    >
      {/* Image */}
      <div className="w-40 h-40 flex-shrink-0 rounded-xl bg-background border border-white/10 overflow-hidden">
        <img
          src={image}
          alt={title}
          className="w-full h-full object-contain"
        />
      </div>

      {/* Content */}
      <div className="flex flex-col justify-between flex-1 min-w-0">
        <div className="flex items-start justify-between gap-3">
          <div className="min-w-0">
            <div className="flex items-center gap-2 text-xs text-text-muted">
              <span>{postedAgo}</span>
              <span className="opacity-50">•</span>
              <span className="truncate">{postedBy} paylaştı</span>
            </div>

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

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

          {/* Vote pill */}
          <div
            onClick={(e) => e.stopPropagation()}
            className="shrink-0 flex items-center gap-1 rounded-full bg-background border border-white/10 p-1"
          >
            <button
              disabled={voting}
              onClick={handleUp}
              className={[
                "p-2 rounded-full transition",
                currentVote === 1 ? "text-green-500" : "text-text-muted hover:text-text",
                voting ? "opacity-60 cursor-not-allowed" : "",
              ].join(" ")}
              aria-label="Upvote"
            >
              <ChevronUp className="w-5 h-5" />
            </button>

            <div className="min-w-[34px] text-center text-sm font-semibold text-text">
              {currentScore ?? 0}
            </div>

            <button
              disabled={voting}
              onClick={handleDown}
              className={[
                "p-2 rounded-full transition",
                currentVote === -1 ? "text-red-500" : "text-text-muted hover:text-text",
                voting ? "opacity-60 cursor-not-allowed" : "",
              ].join(" ")}
              aria-label="Downvote"
            >
              <ChevronDown className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* Bottom actions */}
        <div className="flex items-center justify-between mt-4">
          <div className="flex items-center gap-4 text-sm text-text-muted">
            <span className="inline-flex items-center gap-2">
              <MessageCircle className="w-4 h-4" />
              {comments}
            </span>

            <button
              type="button"
              onClick={(e) => {
                e.stopPropagation()
                // burada share handler yazarsın
              }}
              className="inline-flex items-center gap-2 hover:text-text transition"
            >
              <Share2 className="w-4 h-4" />
              Paylaş
            </button>
          </div>

          <button
            onClick={(e) => {
              e.stopPropagation()
              // CTA handler
            }}
            className="bg-primary text-black px-4 py-2 rounded-xl font-semibold hover:bg-primary-hover transition"
          >
            Fırsatı kap
          </button>
        </div>
      </div>
    </div>
  )
}
