import { createSignal, onMount } from "solid-js"

interface Review {
    reviewID: number;
    discordID: string;
    reviewText: string;
    timestamp: string;
}

interface NeoReview extends Review {
    global_name: string;
    username: string
}

export default function Reviews() {
    const [reviews, setReviews] = createSignal<NeoReview[]>([]);
    onMount(() => {
        fetch("https://api.review.exhq.dev/getreviews")
            .then(response => response.json())
            .then((data: Review[]) => {
                const promises = data.map(review => (
                    fetch(`https://discordlookup.mesalytic.moe/v1/user/${review.discordID}`)
                        .then(response => response.json())
                        .then(user => ({
                            ...review,
                            global_name: user.global_name,
                            username: user.username
                        }))
                ));

                Promise.all(promises)
                    .then(yeah => {
                        setReviews(yeah);
                    })
                    .catch(error => console.error("Error fetching Discord user data:", error));
            })
            .catch(error => console.error("Error fetching reviews:", error));
    });


    return (
        <div class="actualreviewdiv">
            {reviews().length > 0 ? (
                reviews().reverse().map((review) => (
                    <div>
                        <SingleReview {...review} />
                    </div>
                ))
            ) : (
                <div>Loading reviews...</div>
            )}
        </div>
    )
}


function SingleReview(props: NeoReview) {
    console.log(props.global_name)
    return <div class="singlereview">
        <img src={`https://dp.nea.moe/avatar/${props.discordID}.png`} />
        <div class="reviewinfo">
            <div class="reviewname"> {props.global_name === null? props.username : props.global_name} </div>
            <div class="reviewtext"> {props.reviewText}</div>
        </div>
    </div>
}