"use client"

import { useEffect, useState } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Users } from "lucide-react"
import Link from "next/link"
import { getApiUrl } from "@/lib/api-config"

export function UserGroupsList({ userId }: { userId: number }) {
    const [groups, setGroups] = useState<any[]>([])
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        const token = localStorage.getItem("token")
        if (!token) return

        fetch(`${getApiUrl()}/users/${userId}/groups`, {
            headers: { Authorization: `Bearer ${token}` }
        })
            .then(res => res.json())
            .then(data => setGroups(data))
            .catch(err => console.error(err))
            .finally(() => setLoading(false))
    }, [userId])

    if (loading) return <div>Loading groups...</div>

    if (groups.length === 0) {
        return <div className="text-muted-foreground">No groups joined yet.</div>
    }

    return (
        <div className="grid gap-4 md:grid-cols-2">
            {groups.map((group) => (
                <Link key={group.id} href={`/groups/${group.id}`}>
                    <Card className="hover:bg-muted/50 transition-colors">
                        <CardHeader className="p-4 pb-2">
                            <CardTitle className="text-base">{group.name}</CardTitle>
                        </CardHeader>
                        <CardContent className="p-4 pt-0">
                            <p className="text-xs text-muted-foreground line-clamp-1 mb-2">
                                {group.description}
                            </p>
                            <div className="flex items-center text-xs text-muted-foreground">
                                <Users className="mr-1 h-3 w-3" />
                                Member
                            </div>
                        </CardContent>
                    </Card>
                </Link>
            ))}
        </div>
    )
}
