'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { joinRound } from '@/app/actions/rounds'
import { Button } from '@/components/ui/button'

type Props = {
  roundId: string
  round: {
    name: string | null
    date: string
    holesCount: number
    course: { name: string }
    tee: { name: string; color: string }
  }
}

export function JoinRound({ roundId, round }: Props) {
  const router = useRouter()
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function handleJoin() {
    setLoading(true)
    setError(null)

    const result = await joinRound(roundId)

    if (result.error) {
      setError(result.error)
      setLoading(false)
      return
    }

    router.push(`/rounds/${roundId}`)
  }

  return (
    <div className="flex min-h-screen items-center justify-center p-6">
      <div className="w-full max-w-sm space-y-6">
        <div className="space-y-1 text-center">
          <div className="text-4xl">⛳</div>
          <h1 className="text-xl font-bold">You&apos;re invited!</h1>
        </div>

        <div className="rounded-xl border p-4 space-y-2">
          <div className="font-semibold">{round.course.name}</div>
          <div className="text-sm text-muted-foreground space-y-1">
            {round.name && <div>{round.name}</div>}
            <div className="flex items-center gap-2">
              <div
                className="h-3 w-3 rounded-full border"
                style={{ backgroundColor: round.tee.color }}
              />
              {round.tee.name} tees · {round.holesCount} holes
            </div>
            <div>{new Date(round.date).toLocaleDateString()}</div>
          </div>
        </div>

        {error && <p className="text-sm text-destructive">{error}</p>}

        <Button className="w-full" onClick={handleJoin} disabled={loading}>
          {loading ? 'Joining…' : 'Join round'}
        </Button>
      </div>
    </div>
  )
}
