import { Button } from '@/components/ui/button';
import { ArrowBigUp, ArrowBigDown } from 'lucide-react';
import { router, usePage, Link } from '@inertiajs/react';
import { vote } from '@/actions/App/Http/Controllers/Forum/PostController';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { SharedData } from '@/types';

interface Props {
    postId: number;
    votesCount: number;
    userVote?: 'up' | 'down' | null;
    size?: 'sm' | 'default';
}

export function VoteControl({ postId, votesCount, userVote, size = 'default' }: Props) {
    const { auth } = usePage<SharedData>().props;
    const isAuthenticated = !!auth.user;

    const handleVote = (type: 'up' | 'down') => {
        if (!isAuthenticated) {
            // Redirect to login
            router.visit('/login');
            return;
        }
        
        router.post(vote.url(postId), { type }, {
            preserveScroll: true,
            onError: (errors) => {
                if(errors.error){
                    toast.error(errors.error);
                }
            }
        });
    };

    return (
        <div className={cn("flex flex-col items-center gap-1", size === 'sm' && "transform scale-90")}>
            <Button
                variant="ghost"
                size="sm"
                className={cn(
                    "h-8 w-8 p-0 hover:bg-forest/10 hover:text-forest transition-colors",
                    userVote === 'up' && "text-forest bg-forest/10"
                )}
                onClick={() => handleVote('up')}
            >
                <ArrowBigUp className={cn("h-6 w-6", userVote === 'up' && "fill-current")} />
            </Button>
            
            <span className={cn(
                "font-bold text-sm",
                userVote === 'up' && "text-forest",
                userVote === 'down' && "text-red-500"
            )}>
                {votesCount}
            </span>

            <Button
                variant="ghost"
                size="sm"
                className={cn(
                    "h-8 w-8 p-0 hover:bg-red-50 hover:text-red-500 dark:hover:bg-red-950/30 transition-colors",
                    userVote === 'down' && "text-red-500 bg-red-50 dark:bg-red-950/30"
                )}
                onClick={() => handleVote('down')}
            >
                <ArrowBigDown className={cn("h-6 w-6", userVote === 'down' && "fill-current")} />
            </Button>
        </div>
    );
}
