'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { createClient } from '@/lib/supabase/client'
import { Button } from '@/components/ui/button'

type Round = {
  id: string
  name: string | null
  date: string
  holes_count: number
  status: string
  course: { name: string } | null
  tee: { name: string; color: string } | null
}

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

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

    const supabase = createClient()
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const db = supabase as any

    // Get current user's handicap for snapshot
    const { data: profile } = await db
      .from('profiles')
      .select('handicap_index')
      .eq('id', userId)
      .single()

    // Get tee data for course handicap
    const { data: tee } = await db
      .from('tees')
      .select('course_rating, slope_rating')
      .eq('id', round.id) // note: round.tee.id would be better — using server action is cleaner
      .single()

    const { data: roundData } = await db
      .from('rounds')
      .select('tee_id, course:courses(par)')
      .eq('id', round.id)
      .single()

    const { data: teeData } = roundData?.tee_id
      ? await db
          .from('tees')
          .select('course_rating, slope_rating')
          .eq('id', roundData.tee_id)
          .single()
      : { data: null }

    const handicapIndex = profile?.handicap_index ?? null
    const courseHandicap =
      handicapIndex !== null && teeData && roundData?.course
        ? Math.round(
            handicapIndex * (teeData.slope_rating / 113) +
              (teeData.course_rating - roundData.course.par),
          )
        : null

    const { error: joinError } = await db.from('round_players').insert({
      round_id: round.id,
      user_id: userId,
      role: 'player',
      handicap_index: handicapIndex,
      course_handicap: courseHandicap,
    })

    if (joinError) {
      setError(joinError.message)
      setLoading(false)
      return
    }

    // Mark invite as accepted
    await db
      .from('round_invites')
      .update({ accepted_at: new Date().toISOString() })
      .eq('round_id', round.id)
      .eq('email', (await supabase.auth.getUser()).data.user?.email)

    router.push(`/rounds/${round.id}`)
  }

  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.holes_count} 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>
  )
}
