'use client';

import {
    Tooltip,
    TooltipContent,
    TooltipPortal,
} from "@/components/ui/tooltip";
import { ButtonWithTooltip } from "@/components/ui/button";
import { Star } from "lucide-react";
import { useUpdateDay } from "@lifetracker/shared-react/hooks/days";
import { useState } from "react";
import { toast } from "@/components/ui/use-toast";

export function MoodStars({
    day: initialDay,
    maximum = 10,
}) {

    const [day, setDay] = useState(initialDay);

    const { mutate: updateDay, isPending } = useUpdateDay({
        onSuccess: (res, req, meta) => {
            setDay(res);
            toast({
                description: "Rating updated!",
            });
        },
    });
    const setStars = (newStars: number) => {
        if (day.mood == newStars) {
            // Nothing to do here
            return;
        }
        updateDay(
            {
                dateQuery: day.date,
                mood: newStars,
            },
            {
                onError: (e) => {
                    toast({
                        description: e.message,
                        variant: "destructive",
                    });
                },
            },
        );
    };

    return (
        <Tooltip delayDuration={500}>
            <div className="flex max-w-full items-center gap-1">
                {Array.from({ length: maximum }).map((_, i) => (
                    <ButtonWithTooltip
                        key={i}
                        delayDuration={500}
                        tooltip={`Set ${i + 1} star rating`}
                        size="none"
                        variant="ghost"
                        className="align-middle text-gray-400"
                        onClick={() => setStars(i + 1)}
                    >
                        {i < day.mood
                            ? <Star fill="yellow" className="size-4" />
                            : <Star className="size-4" />
                        }
                    </ButtonWithTooltip>
                ))}
            </div>
            <TooltipPortal>
                <TooltipContent side="bottom" className="max-w-[40ch] break-words">
                    Hi
                </TooltipContent>
            </TooltipPortal>
        </Tooltip >
    )
}