import { useState } from 'react';
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { PawPrint } from 'lucide-react';
import { router } from '@inertiajs/react';
import { toast } from 'sonner';
import { toggleFavorite } from '@/routes/teams/animals';
import { type Team } from '@/types';
import { TeamAnimalCard, TeamAnimalEmptyState } from '@/components/team/animals';

interface Props {
    team?: Team | null;
    teamAnimals: any[];
    canManageMembers: boolean;
    setManageAnimalsOpen: (open: boolean) => void;
}

export default function TeamAnimalsTab({
    team,
    teamAnimals,
    canManageMembers,
    setManageAnimalsOpen,
}: Props) {
    const [favoriteToggling, setFavoriteToggling] = useState<number | null>(null);

    const handleToggleFavorite = (animalId: number, currentStatus: boolean, e: React.MouseEvent) => {
        e.stopPropagation();
        setFavoriteToggling(animalId);

        const data = {
            animal_id: animalId,
            team_id: team?.id,
            is_favorite: !currentStatus,
        };

        router.post(toggleFavorite().url, data, {
            onSuccess: () => {
                toast.success(`Animal ${!currentStatus ? 'marcado como destacado' : 'desmarcado como destacado'}`);
                router.reload({ only: ['teamAnimals'] });
            },
            onError: (errors) => {
                toast.error('Error al actualizar el estado del animal');
                console.error('Error actualizando favorito:', errors);
            },
            onFinish: () => {
                setFavoriteToggling(null);
            }
        });
    };

    return (
        <Card className="rounded-xl">
            <CardHeader className="flex flex-row items-start justify-between rounded-xl">
                <div>
                    <CardTitle>Animales del equipo</CardTitle>
                    <CardDescription>
                        {teamAnimals?.length > 0
                            ? `${teamAnimals.length} animales representan a tu equipo`
                            : 'Animales que representan oficialmente al equipo en eventos o exposiciones.'}
                    </CardDescription>
                </div>
                <div className="flex items-center gap-2">
                    <Button
                        variant="default"
                        className="rounded-xl"
                        onClick={() => setManageAnimalsOpen(true)}
                        disabled={!canManageMembers}
                    >
                        <PawPrint className="w-4 h-4 mr-2" />
                        Gestionar animales
                    </Button>
                </div>
            </CardHeader>
            <CardContent>
                {teamAnimals?.length > 0 ? (
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                        {teamAnimals.map((animal) => (
                            <TeamAnimalCard
                                key={animal.id}
                                animal={animal}
                                onToggleFavorite={canManageMembers ? handleToggleFavorite : undefined}
                                isToggling={favoriteToggling === animal.id}
                            />
                        ))}
                    </div>
                ) : (
                    <TeamAnimalEmptyState
                        canManageAnimals={canManageMembers}
                        onManageClick={() => setManageAnimalsOpen(true)}
                    />
                )}
            </CardContent>
        </Card>
    );
}
