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

import { ChevronUp, ChevronDown, MessageCircle, Share2 } from "lucide-react"
import { timeAgo } from "../../utils/timeAgo"
import { scoreToHeat } from "../../utils/heat"
import type { DealCard } from "../../models/deal/DealCard"

type DealCardMainProps = {
  deal: DealCard
  onRequireLogin: () => void
}

export default function DealCardMain({ deal, onRequireLogin }: DealCardMainProps) {
  const navigate = useNavigate()
  const { token, isAuthenticated } = useAuth()

  const id = deal.id
  const image = deal.imageUrl || "/placeholder.png"
  const title = deal.title
  const store = deal.seller?.name ?? "Bilinmiyor"
  const postedBy = deal.user?.username ?? "unknown"
  const postedAgo = useMemo(() => timeAgo(deal.createdAt), [deal.createdAt])
  const priceText = deal.price ? `${deal.price}₺` : ""
  const comments = deal.commentsCount

  const isPending = deal.status === "PENDING"
  const isRejected = deal.status === "REJECTED"
  const showVotes = !(isPending || isRejected)

  const hasUrl = !isRejected && typeof deal.url === "string" && deal.url.trim().length > 0

  const [currentScore, setCurrentScore] = useState<number>(deal.score)
  const [currentVote, setCurrentVote] = useState<1 | 0 | -1>(deal.myVote)
  const [voting, setVoting] = useState(false)

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

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

    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)
      }
    } 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}`)

  const handleGoToDeal = (e: React.MouseEvent) => {
    e.stopPropagation()
    if (isRejected) return
    if (!hasUrl) return
    window.open(deal.url as string, "_blank", "noopener,noreferrer")
  }

  // Using scoreToHeat function to get the color for the score
  const { color } = scoreToHeat(currentScore)

  return (  <div
    onClick={handleCardClick}
    className={[ "relative flex gap-4 bg-surface rounded border border-white/10",
      "hover:border-white/20 transition-shadow duration-300 cursor-pointer", 
      "shadow-sm hover:shadow-lg", // Reduced shadow on default, and slightly larger on hover
      "h-auto", // Yüksekliği otomatik yapıyoruz, resme ve içeriğe göre
    ].join(" ")}
  >
    {isPending && (
      <div className="absolute top-3 right-3 z-10">
        <span
          className="inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold
          border border-amber-500/30
          bg-[linear-gradient(90deg,var(--color-notice-warning-soft),var(--color-surface))] 
          text-text shadow-sm"
        >
          İncelemede
        </span>
      </div>
    )}

    {isRejected && (
      <div className="absolute top-3 right-3 z-10">
        <span
          className="inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold
          border border-rose-500/30
          bg-[linear-gradient(90deg,var(--color-notice-danger-soft),var(--color-surface))] 
          text-text shadow-sm"
        >
          Reddedildi
        </span>
      </div>
    )}

    {/* Fotoğraf kısmı - En solda */}
    <div className="w-57 h-57 flex-shrink-1 rounded-l-l bg-background overflow-hidden">
      <img src={image} alt={title} className="w-full h-full object-contain" />
    </div>

    {/* İçerik kısmı - padding sadece burada olacak */}
    <div className="flex flex-col justify-between flex-1 min-w-0 p-4">
      {/* İlk Satır - Voteler ve Ne Zaman Gönderildi */}
      <div className="flex items-center justify-between gap-3 mb-3">
        {/* Voteler */}
        {showVotes && (
 <div
  onClick={(e) => e.stopPropagation()}
  className="shrink-0 flex items-center gap-1 rounded-2xl bg-background border border-white p-1"
>
  <button
    disabled={voting}
    onClick={handleUp}
    className={[
      "p-1 rounded-full transition", // padding'i küçülttük
      currentVote === 1 ? "text-green-500" : "text-text-muted hover:text-text",
      voting ? "opacity-60 cursor-not-allowed" : "cursor-pointer",
    ].join(" ")}
    aria-label="Upvote"
  >
    <ChevronUp className="w-4 h-4" /> {/* icon boyutunu küçülttük */}
  </button>

  <div
    className="min-w-[34px] text-center text-s font-bold text-text" // font-size'ı text-xs olarak küçülttük
    style={{ color }}
  >
    {currentScore ?? 0}°
  </div>

  <button
    disabled={voting}
    onClick={handleDown}
    className={[
      "p-1 rounded-full transition", // padding'i küçülttük
      currentVote === -1 ? "text-red-500" : "text-text-muted hover:text-text ",
      voting ? "opacity-60 cursor-not-allowed" : "cursor-pointer",
    ].join(" ")}
    aria-label="Downvote"
  >
    <ChevronDown className="w-4 h-4" /> {/* icon boyutunu küçülttük */}
  </button>
</div>
        )}
        
        {/* Gönderilme Zamanı */}
        <div className="flex items-center text-s text-text-muted">
          <span>{postedAgo}</span>
        </div>
      </div>

      {/* Başlık ve Açıklama */}
      <div className="min-w-0">
        <h2 className="text-xl font-bold text-text mt-1 hover:text-primary line-clamp-2">
          {title}
        </h2>

        <div className="flex items-baseline gap-2 ">
          <span className="text-primary text-2xl font-semibold">{priceText}</span>
          <span className="text-sm text-text-muted">{store}</span>
        </div>

        {/* Fiyatın altına description (açıklama) ekliyoruz */}
        {deal.description && (
          <p className="text-sm text-text-muted mt-2 line-clamp-2">{deal.description}</p>
        )}
      </div>

      <div className="flex items-center justify-between mt-4">
        <div className="flex items-center gap-4 text-sm text-text-muted">
          {/* Yorum kısmı üzerine gelince turuncu olmalı */}
          <span className="inline-flex items-center gap-2 hover:text-orange-500 transition cursor-pointer">
            <MessageCircle className="w-4 h-4" />
            {comments}
          </span>

          {/* Paylaş butonunun yanında Avatar ve Kullanıcı İsmi */}
          <button
            type="button"
            onClick={(e) => e.stopPropagation()}
            className="inline-flex items-center gap-2 hover:text-orange-500 transition cursor-pointer"
          >
            <Share2 className="w-4 h-4" />
            Paylaş
          </button>

          {/* Paylaşanın Avatar ve İsmi */}
          <div className="flex items-center gap-2 hover:text-orange-500 transition cursor-pointer">
            {/* Avatar */}
            {deal.user?.avatarUrl && (
              <img
                src={deal.user.avatarUrl}
                alt={deal.user.username}
                className="w-6 h-6 rounded-full object-cover"
              />
            )}

            <span 
              className="text-xs text-text-muted hover:text-orange-500"
              onClick={(e) => {
                e.stopPropagation(); // Yönlendirme sırasında yayılmayı engelle
                navigate(`/user/${deal.user?.username}`); // Kullanıcı profil sayfasına git
              }}
            >
              {deal.user?.username} tarafından paylaşıldı.
            </span>
          </div>
        </div>

        {hasUrl && (
          <button
            type="button"
            onClick={handleGoToDeal}
            className="bg-primary text-white px-4 py-2 rounded-xl font-semibold hover:bg-primary-hover active:scale-[0.98] transition shadow-sm hover:shadow-md focus:outline-none focus:ring-2 focus:ring-primary/40 cursor-pointer"
          >
            Fırsata git
          </button>
        )}
      </div>
    </div>
  </div>
  )
}
