"use client"

import { Button } from "@/components/ui/button"
import { useState } from "react"
import { getApiUrl } from "@/lib/api-config"

export function JoinGroupButton({ groupId }: { groupId: number }) {
    const [joined, setJoined] = useState(false)
    const [loading, setLoading] = useState(false)

    const handleJoin = async () => {
        const token = localStorage.getItem("token")
        if (!token) {
            alert("Please log in to join.")
            return
        }

        setLoading(true)
        try {
            const res = await fetch(`${getApiUrl()}/groups/${groupId}/join`, {
                method: "POST",
                headers: { Authorization: `Bearer ${token}` }
            })

            if (res.ok) {
                setJoined(true)
            } else {
                const data = await res.json()
                if (data.detail === "Already a member") {
                    setJoined(true)
                } else {
                    alert("Failed to join group")
                }
            }
        } catch (err) {
            console.error(err)
        } finally {
            setLoading(false)
        }
    }

    if (joined) {
        return <Button variant="outline" disabled>Joined</Button>
    }

    return (
        <Button onClick={handleJoin} disabled={loading}>
            {loading ? "Joining..." : "Join Group"}
        </Button>
    )
}
