import { Link, usePage } from '@inertiajs/react';
import axios from 'axios';
import { useState } from 'react';

import { AuthorBadge } from '@/components/AuthorBadge';
import UserAvatar from '@/components/UserAvatar';
import { VipBadge } from '@/components/VipBadge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { useTranslation } from '@/contexts/LanguageContext';
import { UserSummary } from '@/types/games';

interface Props {
    user: UserSummary;
    showFollowButton?: boolean;
}

function displayNameOf(user: UserSummary): string {
    return [user.first_name, user.last_name].filter(Boolean).join(' ') || user.username;
}

export default function UserCard({ user, showFollowButton = true }: Props) {
    const { t } = useTranslation();
    const { props } = usePage<{ features?: { follows?: boolean } }>();
    const followsEnabled = props.features?.follows ?? true;
    const [following, setFollowing] = useState(user.isFollowing);
    const [busy, setBusy] = useState(false);
    const displayName = displayNameOf(user);

    function toggle(e: React.MouseEvent) {
        e.preventDefault();
        e.stopPropagation();
        if (busy || user.isSelf) return;
        setBusy(true);
        const next = !following;
        const req = next
            ? axios.post(`/users/${user.id}/follow`)
            : axios.delete(`/users/${user.id}/follow`);
        req
            .then(() => setFollowing(next))
            .catch(() => {/* swallow; UI stays at last known state */})
            .finally(() => setBusy(false));
    }

    return (
        <Link href={`/profile/${user.username}`}>
            <Card size="sm" className="rounded-md ring-0 border bg-card hover:bg-muted transition-colors">
                <CardContent className="flex items-center gap-3 py-1">
                    <UserAvatar user={user} size={48} />
                    <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-1.5 truncate">
                            <span className="font-semibold truncate">{displayName}</span>
                            {user.is_author && <AuthorBadge iconOnly />}
                            {user.is_vip && <VipBadge iconOnly />}
                        </div>
                        <div className="flex items-center gap-1.5 text-xs text-muted-foreground truncate">
                            <span>@{user.username}</span>
                            {(user.rank?.reward_title || user.level) && (
                                <span className="inline-flex items-center gap-1 rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide">
                                    {user.rank?.reward_title ?? t('Lv. :level', { level: user.level ?? 1 })}
                                </span>
                            )}
                        </div>
                    </div>
                    {showFollowButton && !user.isSelf && followsEnabled && (
                        <Button
                            type="button"
                            onClick={toggle}
                            disabled={busy}
                            variant={following ? 'secondary' : 'default'}
                            size="sm"
                            className="h-8 px-3"
                        >
                            {following ? t('Unfollow') : t('Follow')}
                        </Button>
                    )}
                </CardContent>
            </Card>
        </Link>
    );
}
