import { motion } from "framer-motion";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { useTranslation } from "react-i18next";
import { Loader2, Coffee, Gamepad2, Palette, Gift, type LucideIcon } from "lucide-react";
import { useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import { useState } from "react";
// We don't have types shared for specific API responses yet, so using any for now or defining locally
type Reward = {
    id: string;
    title: string;
    description: string | null;
    cost: number;
    icon: string;
    type: string;
    owned?: boolean;
};

type RewardCardProps = {
    reward: Reward;
    userXp: number;
    userId: string;
};

const iconMap: Record<string, LucideIcon> = {
    "coffee": Coffee,
    "gamepad-2": Gamepad2,
    "palette": Palette,
    "gift": Gift
};

export const RewardCard = ({ reward, userXp, userId }: RewardCardProps) => {
    const { t } = useTranslation();
    const { toast } = useToast();
    const queryClient = useQueryClient();
    const [isLoading, setIsLoading] = useState(false);

    const canAfford = userXp >= reward.cost;
    const isOwned = reward.owned;

    const IconComponent = iconMap[reward.icon] || Gift; // Fallback

    const handleBuy = async () => {
        if (!canAfford && !isOwned) return;
        setIsLoading(true);
        try {
            const res = await apiRequest("POST", "/api/rewards/purchase", {
                rewardId: reward.id
            });
            await res.json();

            toast({
                title: t("rewards.buySuccess"), // Need to add this key or use generic
                description: t("rewards.itemPurchased", { item: t(reward.title) }),
            });

            // Refetch rewards and user (to update XP)
            queryClient.invalidateQueries({ queryKey: ["/api/rewards"] });
            queryClient.invalidateQueries({ queryKey: ["/api/user"] }); // Assuming user fetch uses this key
            queryClient.invalidateQueries({ queryKey: ["/api/users/current"] }); // Or this
        } catch (error) {
            toast({
                title: t("rewards.buyFailed"),
                description: t("rewards.insufficientFunds"),
                variant: "destructive"
            });
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <motion.div
            whileHover={{ scale: 1.02 }}
            whileTap={{ scale: 0.98 }}
        >
            <Card className={`relative overflow-hidden p-6 transition-colors ${isOwned ? "bg-primary/10 border-primary/20" : "bg-card hover:border-primary/50"
                }`}>
                <div className="flex flex-col items-center gap-4 text-center">
                    <div className={`p-4 rounded-full ${isOwned ? "bg-primary/20 text-primary" : "bg-muted text-muted-foreground"
                        }`}>
                        <IconComponent className="h-8 w-8" />
                    </div>

                    <div className="space-y-1">
                        <h3 className="font-bold text-lg">{t(reward.title)}</h3>
                        <p className="text-sm text-muted-foreground">{t(reward.description || "")}</p>
                    </div>

                    <div className="mt-2 w-full">
                        {isOwned ? (
                            <Button variant="outline" className="w-full cursor-default disabled:opacity-100" disabled>
                                {t("rewards.owned")}
                            </Button>
                        ) : (
                            <Button
                                className="w-full gap-2"
                                disabled={!canAfford || isLoading}
                                onClick={handleBuy}
                                variant={canAfford ? "default" : "secondary"}
                            >
                                {isLoading ? (
                                    <Loader2 className="h-4 w-4 animate-spin" />
                                ) : (
                                    <>
                                        {t("rewards.buy")}
                                        <span className="font-mono text-xs bg-black/20 px-2 py-0.5 rounded">
                                            {reward.cost} XP
                                        </span>
                                    </>
                                )}
                            </Button>
                        )}
                    </div>
                </div>
            </Card>
        </motion.div>
    );
};
