'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 { format } from 'date-fns';
import { useRouter } from "next/navigation";


export function MoodStars({
    day,
    maximum = 10,
}) {
    const router = useRouter();
    const { mutate: updateDay, isPending } = useUpdateDay({
        onSuccess: () => {
            toast({
                description: "Rating updated!",
            });
            router.refresh();
        },
    });
    const setStars = (newStars: number) => {
        if (day.mood == newStars) {
            // Nothing to do here
            return;
        }
        updateDay(
            {
                dateQuery: format(day.date, "yyyy-MM-dd"),
                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 >
    )
}