"use client"

import { useState, useEffect } from "react"
import { RatingInput, RatingBadge } from "@/components/ui/rating-input"
import { getApiUrl } from "@/lib/api-config"

interface EntityRatingProps {
    entityType: "show" | "song" | "venue" | "tour" | "performance"
    entityId: number
    compact?: boolean
}

export function EntityRating({ entityType, entityId, compact = false }: EntityRatingProps) {
    const [userRating, setUserRating] = useState(0)
    const [averageRating, setAverageRating] = useState(0)
    const [loading, setLoading] = useState(false)
    const [hasRated, setHasRated] = useState(false)

    useEffect(() => {
        // Fetch average rating
        fetch(`${getApiUrl()}/social/ratings/average?${entityType}_id=${entityId}`)
            .then(res => res.ok ? res.json() : 0)
            .then(data => setAverageRating(data || 0))
            .catch(() => setAverageRating(0))
    }, [entityType, entityId])

    const handleRate = async (score: number) => {
        const token = localStorage.getItem("token")
        if (!token) {
            alert("Please log in to rate.")
            return
        }

        setLoading(true)
        try {
            const body: Record<string, unknown> = { score }
            body[`${entityType}_id`] = entityId

            const res = await fetch(`${getApiUrl()}/social/ratings`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    Authorization: `Bearer ${token}`
                },
                body: JSON.stringify(body)
            })

            if (!res.ok) throw new Error("Failed to submit rating")

            const data = await res.json()
            setUserRating(data.score)
            setHasRated(true)

            // Re-fetch average
            fetch(`${getApiUrl()}/social/ratings/average?${entityType}_id=${entityId}`)
                .then(res => res.ok ? res.json() : averageRating)
                .then(setAverageRating)
        } catch (err) {
            console.error(err)
            alert("Error submitting rating")
        } finally {
            setLoading(false)
        }
    }

    if (compact) {
        return (
            <div className="flex items-center gap-2">
                {averageRating > 0 && (
                    <RatingBadge value={averageRating} />
                )}
            </div>
        )
    }

    return (
        <div className="border rounded-lg p-4 bg-card">
            <div className="flex items-center justify-between mb-3">
                <span className="text-sm font-medium">Your Rating</span>
                {averageRating > 0 && (
                    <span className="text-xs text-muted-foreground">
                        Community avg: <span className="font-medium">{averageRating.toFixed(1)}</span>
                    </span>
                )}
            </div>

            <RatingInput
                value={userRating}
                onChange={handleRate}
                showSlider={true}
            />

            {loading && (
                <p className="text-xs text-muted-foreground mt-2 animate-pulse">
                    Submitting...
                </p>
            )}
            {hasRated && !loading && (
                <p className="text-xs text-green-600 mt-2">
                    Rating saved!
                </p>
            )}
        </div>
    )
}
