import { useQuery } from "@tanstack/react-query";
import { AwardNotComplete } from "./award-not-complete";
import { getAwardsList } from "../../services/api/awards";
import { AwardsResponse, AwardStatus } from "../../types";
import { AwardSkeleton } from "./award-skeleton";
import { handleError } from "../../utility/error-handle";
import { useEffect, useState } from "react";
import { AwardComplete } from "./awards-complete";
import { useUserStore } from "../../store/user";

export const Awards = () => {
    const { user } = useUserStore()
    const [status, setStatus] = useState<AwardStatus>({
        awards: 0,
        my_score: 0
    });
    const { data, isLoading, error } = useQuery({
        queryKey: ["awards"],
        queryFn: getAwardsList
    });

    useEffect(() => {
        handleError(error);
    }, [error]);

    useEffect(() => {
        const awardsTemp: number = data?.data?.length;
        const tempScores: any = data?.data?.filter((award: AwardsResponse) => award?.status === 1);
        const myScore = tempScores?.reduce((totalScore: number, award: AwardsResponse) => totalScore + award?.score, 0);
        setStatus({
            awards: awardsTemp,
            my_score: myScore
        });
    }, [data]);

    if (isLoading) return <AwardSkeleton />;
    return (
        <div className="flex flex-col gap-10">
            <div className="flex flex-row justify-between items-center">
                <p className="font-medium text-xl text-primary-text-color">جوایز ({status?.awards})</p>
                <p className="font-normal text-base text-primary-text-color">امتیازهای من: {status?.my_score}</p>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 gap-6">
                {data?.data?.map((award: AwardsResponse, index: number) => award?.status === 0 ? <AwardNotComplete key={index} award={award} /> : <AwardComplete key={index} award={award} />)}
            </div>
        </div>
    );
};
