import { useState } from 'react'

import { useSendRate, useUserRating } from '../hooks/api'
import { gotError, gotResponse } from '../hooks/useFetch'

import styles from '../styles/StarRating.module.css'

type StarProps = {
    filled: boolean,
    selected: boolean,
    setMyRate?: () => void,
    sendMyRate?: () => void,
    disabled: boolean
}

function Star({ filled, selected, setMyRate, sendMyRate, disabled }: StarProps) {
    return (
        <button
            className={`${styles.star} ${filled ? styles.starFilled : ''} ${selected ? styles.starSelected : ''}`}
            onMouseEnter={setMyRate}
            onFocus={setMyRate}
            onClick={sendMyRate}
            disabled={disabled}
        >&#9733;</button> // star
    )
}

type StarRatingProps = {
    userId: number,
    dynamic?: boolean,
    style?: React.CSSProperties,
}

function StarRating({ userId, dynamic = false }: StarRatingProps) {
    const rating = useUserRating(userId)

    const [myRate, setMyRate] = useState(0)

    const { doSendRate } = useSendRate()

    async function sendMyRate() {
        const res = await doSendRate(myRate, userId)

        if (res) {
            rating.refetch()
        }
    }

    if (!gotResponse(rating)) {
        return (
            <span>Загрузка...</span>
        )
    }

    if (gotError(rating)) {
        return (
            <span className='text-danger'>{rating.error}</span>
        )
    }

    return (
        <span className={styles.starContainer} onMouseLeave={() => setMyRate(0)}>
            {...Array(5).fill(5).map((_, i) => (
                <Star
                    key={i}
                    filled={i < Math.round(rating.data)}
                    selected={i < myRate}
                    setMyRate={() => dynamic && setMyRate(i + 1)}
                    sendMyRate={() => dynamic && void sendMyRate()}
                    disabled={!dynamic}
                />
            ))}
        </span >
    )
}

export default StarRating
