import { Link } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Card, CardContent } from '@/components/ui/card';
import { getFollowingList } from '@/client';
import { UserPlus } from 'lucide-react';

export function FollowingList({ username }: { username: string }) {
    const { data, isLoading, isError } = useQuery({
        queryKey: ['user-following', username],
        queryFn: async () => {
            const resp = await getFollowingList({ path: { username } });
            return resp.data?.data ?? [];
        },
        retry: false,
    });

    if (isLoading) {
        return (
            <Card className="border-border/40">
                <CardContent className="py-8 text-center text-sm text-muted-foreground">
                    Loading following...
                </CardContent>
            </Card>
        );
    }

    if (isError || !data) {
        return (
            <Card className="border-border/40">
                <CardContent className="py-8 text-center text-sm text-muted-foreground">
                    Unable to load following.
                </CardContent>
            </Card>
        );
    }

    if (data.length === 0) {
        return (
            <Card className="border-border/40">
                <CardContent className="py-12 text-center">
                    <UserPlus className="mx-auto h-8 w-8 text-muted-foreground/40" />
                    <p className="mt-2 text-sm text-muted-foreground">Not following anyone yet</p>
                </CardContent>
            </Card>
        );
    }

    return (
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 md:grid-cols-3">
            {data.map((user: { user_uid: string; username: string; display_name?: string | null; avatar_url?: string | null }) => (
                <Link
                    key={user.user_uid}
                    to={`/user/${user.username}`}
                    className="flex items-center gap-3 rounded-lg border border-border/40 p-3 transition-all hover:border-border hover:bg-muted/30"
                >
                    <Avatar className="h-10 w-10">
                        <AvatarImage src={user.avatar_url ?? undefined} />
                        <AvatarFallback className="text-sm">
                            {(user.display_name || user.username).charAt(0).toUpperCase()}
                        </AvatarFallback>
                    </Avatar>
                    <div className="min-w-0">
                        <p className="truncate text-sm font-medium">{user.display_name || user.username}</p>
                        <p className="truncate text-xs text-muted-foreground">@{user.username}</p>
                    </div>
                </Link>
            ))}
        </div>
    );
}
