"use client";
import { Article } from "@/features/posts/_lib/transformers";
import { VoteProps } from "../../types/types";
import { RateChart } from "@/components/chart";
import { ThumbsDown, ThumbsUp } from "lucide-react";
import { api } from "@/lib/trpc/client";
import { PostReactionType } from "@/server/modules/post/types/post-reaction-type.enum";
import { useState } from "react";
import { cn } from "@/lib/utils";
import { TopicsEnum } from "@/config/enums";
import { toast } from "sonner";

export default function VoteWidget({ props, post }: { props: VoteProps; post?: Article }) {
    const [stats, setStats] = useState(post?.stats);

    if (!props || !props?.title || !stats || !post) {
        return null;
    }

    const utils = api.useUtils();

    const { data: userReaction, isFetching } = api.posts.userReaction.useQuery({
        postId: post.id
    });

    const { mutateAsync, isPending } = api.posts.toggleReaction.useMutation({
        onSuccess: async () => {
            await utils.posts.userReaction.invalidate({
                postId: post.id
            });
        }
    });

    const toggleVote = async (type: PostReactionType) => {
        try {
            const res = await mutateAsync({
                postId: post.id,
                type
            });
            if (!res) {
                toast.error("Fejl", {
                    description: "Afstemningsfejl."
                });
                return;
            }
            toast.success("Succes", {
                description: "Din stemme er blevet talt op."
            });
            setStats(res.stats);
        } catch (error) {
            toast.error("Fejl", {
                description: "Afstemningsfejl."
            });
            console.log(error);
        }
    };

    const { title } = props;

    const totalVotes = stats.upvotes + stats.downvotes;
    const votePercent = !!totalVotes ? Math.ceil((stats.upvotes / totalVotes) * 100) : 0;
    const isLiked = userReaction?.type === PostReactionType.LIKE;
    const isDisliked = userReaction?.type === PostReactionType.DISLIKE;

    const isPhoto = post.topic === TopicsEnum.PHOTO;
    const isCityLife = post.topic === TopicsEnum.CITY_LIFE;
    const isOpinion = post.topic === TopicsEnum.OPINION;
    const isProject = post.topic === TopicsEnum.PROJECT;
    const isVision = post.topic === TopicsEnum.VISIONS;

    return (
        <div className='widget-left-col'>
            <div className={cn("vote flex flex-col items-center gap-4", (isPending || isFetching) && "opacity-50")}>
                <h6 className='text-center text-2xl font-bold uppercase'>{title}</h6>
                <div className='flex flex-col items-center gap-2'>
                    <button
                        aria-label='Like'
                        onClick={() => toggleVote(PostReactionType.LIKE)}
                        disabled={isPending}
                        className='transition hover:scale-110'
                    >
                        <ThumbsUp
                            className={cn(
                                "size-8",
                                isLiked &&
                                    (isPhoto || isCityLife
                                        ? "fill-client-orange stroke-client-orange"
                                        : isOpinion
                                          ? "stroke-client-green fill-client-green"
                                          : isProject
                                            ? "stroke-client-green fill-client-green"
                                            : isVision
                                              ? "stroke-client-blue fill-client-blue"
                                              : "stroke-client-red fill-client-red")
                            )}
                        />
                    </button>

                    <div className='flex justify-center'>
                        <RateChart
                            value={votePercent}
                            fillColor={
                                isPhoto || isCityLife
                                    ? "var(--color-client-orange)"
                                    : isOpinion
                                      ? "var(--color-client-green)"
                                      : isProject
                                        ? "var(--color-black)"
                                        : isVision
                                          ? "var(--color-client-blue)"
                                          : "var(--color-client-red)"
                            }
                            emptyColor='var(--color-gray-200)'
                            className='size-28 md:size-34'
                        />
                    </div>

                    <button
                        aria-label='Dislike'
                        onClick={() => toggleVote(PostReactionType.DISLIKE)}
                        disabled={isPending}
                        className='transition hover:scale-110'
                    >
                        <ThumbsDown
                            className={cn(
                                "size-8",
                                isDisliked &&
                                    (isPhoto || isCityLife
                                        ? "fill-client-orange stroke-client-orange"
                                        : isOpinion
                                          ? "stroke-client-green fill-client-green"
                                          : isProject
                                            ? "stroke-client-green fill-client-green"
                                            : isVision
                                              ? "stroke-client-blue fill-client-blue"
                                              : "stroke-client-red fill-client-red")
                            )}
                        />
                    </button>
                </div>
                <p className='px-2 text-center text-neutral-400'>
                    Denne vision har modtaget <span className='text-black'>{votePercent} %</span> positive stemmer
                </p>
                <p className='px-2 text-center text-neutral-400'>
                    Stemmer i alt <span className='text-black'>{totalVotes}</span>
                </p>
            </div>
        </div>
    );
}
