import React, { useState } from 'react';
import axios from 'axios';
import { toast } from 'sonner';
import { ThumbsUp, ThumbsDown } from 'lucide-react';
import { Button } from '@/Components/ui/button';
import { cn } from '@/lib/utils';
import useTranslation from '@/hooks/useTranslation';

export default function VoteButtons({ post, auth, className }) {
    const { t } = useTranslation();

    const [upvotes, setUpvotes] = useState(post.upvotes_count || 0);
    const [downvotes, setDownvotes] = useState(post.downvotes_count || 0);
    const [userVote, setUserVote] = useState(post.user_vote || null);
    const[loading, setLoading] = useState(false);

    const handleVote = async (e, type) => {
        // Prevent clicking the button from activating the wrapper <Link>
        e.preventDefault();
        e.stopPropagation();

        if (!auth?.user) {
            toast.info(t('_login_required_vote', 'Please log in to vote on articles.'));
            return;
        }

        if (loading) return;

        const previousVote = userVote;
        let newUpvotes = upvotes;
        let newDownvotes = downvotes;

        if (userVote === type) {
            setUserVote(null);
            if (type === 'upvote') newUpvotes--;
            else newDownvotes--;
        } else {
            setUserVote(type);
            if (type === 'upvote') {
                newUpvotes++;
                if (previousVote === 'downvote') newDownvotes--;
            } else {
                newDownvotes++;
                if (previousVote === 'upvote') newUpvotes--;
            }
        }

        setUpvotes(newUpvotes);
        setDownvotes(newDownvotes);
        setLoading(true);

        try {
            const res = await axios.post(`/api/posts/${post.id}/vote`, { type });
            setUpvotes(res.data.upvotes_count);
            setDownvotes(res.data.downvotes_count);
            setUserVote(res.data.user_vote);
        } catch (error) {
            toast.error(t('_vote_failed', 'Failed to submit vote.'));
            setUpvotes(post.upvotes_count);
            setDownvotes(post.downvotes_count);
            setUserVote(post.user_vote);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div 
            className={cn("flex items-center bg-muted/40 border border-border rounded-full p-0.5", className)}
            onClick={(e) => { e.preventDefault(); e.stopPropagation(); }}
        >
            <Button 
                variant="ghost" 
                size="sm" 
                onClick={(e) => handleVote(e, 'upvote')}
                disabled={loading}
                className={cn(
                    "rounded-full h-8 px-3 gap-1.5 transition-colors", 
                    userVote === 'upvote' 
                        ? "text-blue-600 bg-blue-100 hover:bg-blue-200 dark:bg-blue-900/30 dark:text-blue-400" 
                        : "text-muted-foreground hover:text-foreground"
                )}
            >
                <ThumbsUp className={cn("w-4 h-4", userVote === 'upvote' && "fill-current")} />
                <span className="text-xs font-semibold">{upvotes > 0 ? upvotes : ''}</span>
            </Button>

            <div className="w-[1px] h-4 bg-border mx-0.5"></div>

            <Button 
                variant="ghost" 
                size="sm" 
                onClick={(e) => handleVote(e, 'downvote')}
                disabled={loading}
                className={cn(
                    "rounded-full h-8 px-3 gap-1.5 transition-colors", 
                    userVote === 'downvote' 
                        ? "text-red-600 bg-red-100 hover:bg-red-200 dark:bg-red-900/30 dark:text-red-400" 
                        : "text-muted-foreground hover:text-foreground"
                )}
            >
                <ThumbsDown className={cn("w-4 h-4 mt-1", userVote === 'downvote' && "fill-current")} />
                <span className="text-xs font-semibold">{downvotes > 0 ? downvotes : ''}</span>
            </Button>
        </div>
    );
}