import { useState, useEffect, useMemo } from 'react'
import { Link } from 'react-router-dom'
import { useAuthStore } from '@/store'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { spreadBetsApi } from '@/api/spread-bets'
import type { SportEventWithBets, SpreadGridBet } from '@/types/sport-event'
import { TeamSide } from '@/types/spread-bet'
import {
  Clock,
  Activity,
  Target,
  TrendingUp,
  TrendingDown,
  BarChart3,
  Grid3X3,
} from 'lucide-react'
import toast from 'react-hot-toast'

interface TradingPanelProps {
  event: SportEventWithBets
  onBetCreated?: () => void
  onBetTaken?: () => void
}

// Helper to format time until game
function formatTimeUntil(gameTime: string): { text: string; urgent: boolean } {
  const now = new Date()
  const game = new Date(gameTime)
  const diff = game.getTime() - now.getTime()

  if (diff <= 0) return { text: 'LIVE', urgent: true }

  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
  const seconds = Math.floor((diff % (1000 * 60)) / 1000)

  if (days > 0) return { text: `${days}d ${hours}h`, urgent: false }
  if (hours > 0) return { text: `${hours}h ${minutes}m`, urgent: hours < 2 }
  if (minutes > 0) return { text: `${minutes}m ${seconds}s`, urgent: true }
  return { text: `${seconds}s`, urgent: true }
}

// Helper to generate half-point spreads only (to prevent ties)
function generateHalfPointSpreads(min: number, max: number): number[] {
  const spreads: number[] = []
  // Round min up to nearest .5
  let start = Math.ceil(min * 2) / 2
  if (start % 1 === 0) start += 0.5
  // Round max down to nearest .5
  let end = Math.floor(max * 2) / 2
  if (end % 1 === 0) end -= 0.5

  for (let s = start; s <= end; s += 1) {
    spreads.push(s)
  }
  return spreads
}

export const TradingPanel = ({ event, onBetCreated, onBetTaken }: TradingPanelProps) => {
  const { isAuthenticated } = useAuthStore()
  const queryClient = useQueryClient()
  const [timeUntil, setTimeUntil] = useState(formatTimeUntil(event.game_time))
  const [selectedSide, setSelectedSide] = useState<'home' | 'away'>('home')
  const [selectedSpread, setSelectedSpread] = useState(event.official_spread)
  const [stakeAmount, setStakeAmount] = useState('')
  const [activeTab, setActiveTab] = useState<'chart' | 'grid'>('chart')

  // Update countdown every second
  useEffect(() => {
    const interval = setInterval(() => {
      setTimeUntil(formatTimeUntil(event.game_time))
    }, 1000)
    return () => clearInterval(interval)
  }, [event.game_time])

  // Calculate market stats
  const marketStats = useMemo(() => {
    let totalVolume = 0
    let totalBets = 0
    let openBets = 0
    let matchedBets = 0
    let homeVolume = 0
    let awayVolume = 0

    Object.entries(event.spread_grid).forEach(([, bets]) => {
      bets.forEach(bet => {
        totalVolume += bet.stake
        totalBets++
        if (bet.status === 'open') openBets++
        if (bet.status === 'matched') matchedBets++
        if (bet.team === 'home') homeVolume += bet.stake
        else awayVolume += bet.stake
      })
    })

    return { totalVolume, totalBets, openBets, matchedBets, homeVolume, awayVolume }
  }, [event.spread_grid])

  // Calculate max volume across all spreads for order book bars
  const maxVolume = useMemo(() => {
    let max = 0
    Object.values(event.spread_grid).forEach(bets => {
      const vol = bets.reduce((sum, b) => sum + b.stake, 0)
      if (vol > max) max = vol
    })
    return max
  }, [event.spread_grid])

  // Generate half-point spreads and split at official line for order book
  const { aboveLine, belowLine, allSpreads } = useMemo(() => {
    const spreads = generateHalfPointSpreads(event.min_spread, event.max_spread)
    const above: number[] = []
    const below: number[] = []

    spreads.forEach(s => {
      if (s > event.official_spread) above.push(s)
      else if (s < event.official_spread) below.push(s)
    })

    return {
      aboveLine: above.sort((a, b) => b - a), // High to low (9.5, 8.5, 7.5...)
      belowLine: below.sort((a, b) => b - a), // High to low (closest to line at top)
      allSpreads: spreads,
    }
  }, [event.min_spread, event.max_spread, event.official_spread])

  // Get all bets with spread info for chart and recent activity
  const allBetsWithSpread = useMemo(() => {
    const bets: (SpreadGridBet & { spread: number })[] = []
    Object.entries(event.spread_grid).forEach(([spread, spreadBets]) => {
      spreadBets.forEach(bet => {
        bets.push({ ...bet, spread: Number(spread) })
      })
    })
    return bets
  }, [event.spread_grid])

  // Recent activity - all bets
  const recentActivity = useMemo(() => {
    return allBetsWithSpread
  }, [allBetsWithSpread])

  // Chart data - volume per spread (half-points only)
  const chartData = useMemo(() => {
    const data: { spread: number; homeVolume: number; awayVolume: number; total: number }[] = []

    allSpreads.forEach(s => {
      const bets = event.spread_grid[s.toString()] || []
      const homeVol = bets.filter(b => b.team === 'home').reduce((sum, b) => sum + b.stake, 0)
      const awayVol = bets.filter(b => b.team === 'away').reduce((sum, b) => sum + b.stake, 0)
      data.push({ spread: s, homeVolume: homeVol, awayVolume: awayVol, total: homeVol + awayVol })
    })

    return data
  }, [event.spread_grid, allSpreads])

  const chartMaxVolume = useMemo(() => {
    return Math.max(...chartData.map(d => d.total), 1)
  }, [chartData])

  // Available bets to take at selected spread
  const availableBets = useMemo(() => {
    const bets = event.spread_grid[selectedSpread.toString()] || []
    return bets.filter(b => b.status === 'open' && b.can_take)
  }, [event.spread_grid, selectedSpread])

  // Create bet mutation
  const createBetMutation = useMutation({
    mutationFn: (data: { event_id: number; spread: number; team: TeamSide; stake_amount: number }) =>
      spreadBetsApi.createBet(data),
    onSuccess: () => {
      toast.success('Bet created successfully!')
      setStakeAmount('')
      queryClient.invalidateQueries({ queryKey: ['sport-event'] })
      onBetCreated?.()
    },
    onError: (error: Error) => {
      toast.error(error.message || 'Failed to create bet')
    },
  })

  // Take bet mutation
  const takeBetMutation = useMutation({
    mutationFn: (betId: number) => spreadBetsApi.takeBet(betId),
    onSuccess: () => {
      toast.success('Bet taken successfully!')
      queryClient.invalidateQueries({ queryKey: ['sport-event'] })
      onBetTaken?.()
    },
    onError: (error: Error) => {
      toast.error(error.message || 'Failed to take bet')
    },
  })

  const handleCreateBet = () => {
    if (!isAuthenticated) {
      toast.error('Please log in to place a bet')
      return
    }

    const amount = parseFloat(stakeAmount)
    if (isNaN(amount) || amount < event.min_bet_amount || amount > event.max_bet_amount) {
      toast.error(`Stake must be between $${event.min_bet_amount} and $${event.max_bet_amount}`)
      return
    }

    createBetMutation.mutate({
      event_id: event.id,
      spread: selectedSpread,
      team: selectedSide === 'home' ? TeamSide.HOME : TeamSide.AWAY,
      stake_amount: amount,
    })
  }

  const handleTakeBet = (betId: number) => {
    if (!isAuthenticated) {
      toast.error('Please log in to take a bet')
      return
    }
    takeBetMutation.mutate(betId)
  }

  // Adjust spread by 1 point (next half-point)
  const adjustSpread = (delta: number) => {
    const newSpread = selectedSpread + delta
    // Ensure it's a valid half-point spread within range
    if (newSpread >= event.min_spread && newSpread <= event.max_spread && newSpread % 1 !== 0) {
      setSelectedSpread(newSpread)
    }
  }

  // Quick stake buttons
  const quickStakes = [25, 50, 100, 250, 500]

  // Order book row renderer
  const renderOrderRow = (spread: number) => {
    const bets = event.spread_grid[spread.toString()] || []
    const homeBets = bets.filter(b => b.team === 'home')
    const awayBets = bets.filter(b => b.team === 'away')
    const homeVolume = homeBets.reduce((sum, b) => sum + b.stake, 0)
    const awayVolume = awayBets.reduce((sum, b) => sum + b.stake, 0)
    const homeOpen = homeBets.filter(b => b.status === 'open' && b.can_take).length
    const awayOpen = awayBets.filter(b => b.status === 'open' && b.can_take).length

    return (
      <button
        key={spread}
        onClick={() => setSelectedSpread(spread)}
        className={`
          grid grid-cols-7 gap-1 py-1.5 px-2 text-xs hover:bg-gray-100 transition-colors w-full
          ${selectedSpread === spread ? 'bg-blue-50 border-l-2 border-blue-500' : ''}
        `}
      >
        {/* Away side */}
        <span className={`text-right ${awayOpen > 0 ? 'text-red-600 font-semibold' : 'text-gray-400'}`}>
          {awayOpen > 0 ? awayOpen : '-'}
        </span>
        <span className="text-right text-red-600 font-mono">
          {awayVolume > 0 ? `$${awayVolume.toLocaleString()}` : '-'}
        </span>
        <div className="col-span-1 flex justify-end">
          <div
            className="h-4 bg-red-200 rounded-l"
            style={{ width: `${maxVolume > 0 ? (awayVolume / maxVolume) * 100 : 0}%`, minWidth: awayVolume > 0 ? '4px' : '0' }}
          />
        </div>

        {/* Spread (center) */}
        <span className={`text-center font-bold ${spread === event.official_spread ? 'text-yellow-600 bg-yellow-100 rounded' : 'text-gray-900'}`}>
          {spread > 0 ? '+' : ''}{spread}
        </span>

        {/* Home side */}
        <div className="col-span-1 flex justify-start">
          <div
            className="h-4 bg-green-200 rounded-r"
            style={{ width: `${maxVolume > 0 ? (homeVolume / maxVolume) * 100 : 0}%`, minWidth: homeVolume > 0 ? '4px' : '0' }}
          />
        </div>
        <span className="text-left text-green-600 font-mono">
          {homeVolume > 0 ? `$${homeVolume.toLocaleString()}` : '-'}
        </span>
        <span className={`text-left ${homeOpen > 0 ? 'text-green-600 font-semibold' : 'text-gray-400'}`}>
          {homeOpen > 0 ? homeOpen : '-'}
        </span>
      </button>
    )
  }

  // Grid view - shows all half-point spreads in a grid format
  const renderGridView = () => {
    return (
      <div className="grid grid-cols-4 sm:grid-cols-6 md:grid-cols-8 lg:grid-cols-10 gap-2">
        {allSpreads.map(spread => {
          const bets = event.spread_grid[spread.toString()] || []
          const homeBets = bets.filter(b => b.team === 'home')
          const awayBets = bets.filter(b => b.team === 'away')
          const homeVolume = homeBets.reduce((sum, b) => sum + b.stake, 0)
          const awayVolume = awayBets.reduce((sum, b) => sum + b.stake, 0)
          const totalBets = bets.length
          const isOfficial = spread === event.official_spread

          return (
            <button
              key={spread}
              onClick={() => setSelectedSpread(spread)}
              className={`
                p-3 rounded-lg border transition-all text-center
                ${selectedSpread === spread ? 'ring-2 ring-blue-500 border-blue-500' : 'border-gray-200 hover:border-gray-300'}
                ${isOfficial ? 'bg-yellow-50 border-yellow-400' : 'bg-white'}
              `}
            >
              <div className={`text-sm font-bold ${isOfficial ? 'text-yellow-600' : 'text-gray-900'}`}>
                {spread > 0 ? '+' : ''}{spread}
              </div>
              <div className="text-xs text-gray-500 mt-1">{totalBets} bets</div>
              <div className="flex justify-center gap-2 mt-1 text-xs">
                <span className="text-green-600">${homeVolume}</span>
                <span className="text-gray-300">|</span>
                <span className="text-red-600">${awayVolume}</span>
              </div>
            </button>
          )
        })}
      </div>
    )
  }

  return (
    <div className="bg-white rounded-xl shadow-sm border overflow-hidden">
      {/* Compact Header - Exchange Style */}
      <div className="bg-gray-800 px-4 py-3 text-white">
        <div className="flex items-center justify-between">
          {/* Left: Teams and Spread */}
          <div className="flex items-center gap-4">
            {/* Home Team */}
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-green-600/20 rounded-full flex items-center justify-center">
                <span className="text-green-400 font-bold">{event.home_team.charAt(0)}</span>
              </div>
              <div>
                <p className="font-semibold text-sm">{event.home_team}</p>
                <p className="text-gray-400 text-xs">HOME</p>
              </div>
            </div>

            {/* Spread */}
            <div className="text-center px-6 border-l border-r border-gray-700">
              <div className="text-gray-400 text-xs">SPREAD</div>
              <div className="text-yellow-400 text-2xl font-bold">
                {event.official_spread > 0 ? '+' : ''}{event.official_spread}
              </div>
              <div className="text-gray-400 text-xs">{event.league}</div>
            </div>

            {/* Away Team */}
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-red-600/20 rounded-full flex items-center justify-center">
                <span className="text-red-400 font-bold">{event.away_team.charAt(0)}</span>
              </div>
              <div>
                <p className="font-semibold text-sm">{event.away_team}</p>
                <p className="text-gray-400 text-xs">AWAY</p>
              </div>
            </div>
          </div>

          {/* Center: Market Stats */}
          <div className="flex items-center gap-6 px-6 border-l border-gray-700">
            <div className="text-center">
              <p className="text-gray-400 text-xs">Volume</p>
              <p className="font-mono font-semibold">${marketStats.totalVolume.toLocaleString()}</p>
            </div>
            <div className="text-center">
              <p className="text-gray-400 text-xs">Open</p>
              <p className="font-mono font-semibold text-green-400">{marketStats.openBets}</p>
            </div>
            <div className="flex items-center gap-2">
              <TrendingUp size={14} className="text-green-400" />
              <span className="text-green-400 font-mono text-sm">${marketStats.homeVolume.toLocaleString()}</span>
            </div>
            <div className="flex items-center gap-2">
              <TrendingDown size={14} className="text-red-400" />
              <span className="text-red-400 font-mono text-sm">${marketStats.awayVolume.toLocaleString()}</span>
            </div>
          </div>

          {/* Right: Countdown */}
          <div className="flex items-center gap-3 pl-6 border-l border-gray-700">
            <div className={`
              flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-semibold
              ${timeUntil.urgent ? 'bg-red-500/20 text-red-400 animate-pulse' : 'bg-gray-700 text-gray-300'}
            `}>
              <Clock size={16} />
              <span>{timeUntil.text}</span>
            </div>
            <div className="text-right">
              <p className="text-gray-400 text-xs">
                {new Date(event.game_time).toLocaleDateString('en-US', {
                  weekday: 'short',
                  month: 'short',
                  day: 'numeric',
                })}
              </p>
              <p className="text-gray-300 text-xs">
                {new Date(event.game_time).toLocaleTimeString('en-US', {
                  hour: 'numeric',
                  minute: '2-digit',
                })}
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Main Content - fixed height container */}
      <div className="grid grid-cols-12 divide-x divide-gray-200 h-[600px] overflow-hidden">
        {/* Left - Order Book */}
        <div className="col-span-3 flex flex-col overflow-hidden bg-gray-50">
          <div className="p-3 border-b bg-white">
            <h3 className="font-semibold text-gray-900 flex items-center gap-2 text-sm">
              <Activity size={14} className="text-gray-400" />
              Order Book
            </h3>
          </div>

          {/* Column Header */}
          <div className="grid grid-cols-7 gap-1 py-1.5 px-2 text-xs text-gray-500 border-b bg-white">
            <span className="text-right">{event.away_team.slice(0, 4)}</span>
            <span className="text-right">Vol</span>
            <span></span>
            <span className="text-center">Spread</span>
            <span></span>
            <span className="text-left">Vol</span>
            <span className="text-left">{event.home_team.slice(0, 4)}</span>
          </div>

          {/* Above official line - aligned to bottom */}
          <div className="flex-1 overflow-y-auto flex flex-col justify-end border-b border-gray-200 bg-white">
            <div className="px-2">
              {aboveLine.map(spread => renderOrderRow(spread))}
            </div>
          </div>

          {/* Official Line */}
          <div className="bg-yellow-50 border-y-2 border-yellow-400 px-2 flex-shrink-0">
            {renderOrderRow(event.official_spread)}
          </div>

          {/* Below official line - aligned to top */}
          <div className="flex-1 overflow-y-auto bg-white">
            <div className="px-2">
              {belowLine.map(spread => renderOrderRow(spread))}
            </div>
          </div>
        </div>

        {/* Center - Chart/Grid with Tabs */}
        <div className="col-span-6 flex flex-col overflow-hidden">
          {/* Tabs */}
          <div className="flex border-b bg-white">
            <button
              onClick={() => setActiveTab('chart')}
              className={`flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-colors ${
                activeTab === 'chart'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700'
              }`}
            >
              <BarChart3 size={16} />
              Chart
            </button>
            <button
              onClick={() => setActiveTab('grid')}
              className={`flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-colors ${
                activeTab === 'grid'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700'
              }`}
            >
              <Grid3X3 size={16} />
              Grid
            </button>
          </div>

          {/* Tab Content */}
          <div className="flex-1 flex flex-col overflow-hidden p-4 min-h-0">
            {activeTab === 'chart' ? (
              <div className="flex flex-col h-full min-h-0">
                {/* Chart Section */}
                <div className="flex-1 flex flex-col min-h-0">
                  <h3 className="font-semibold text-gray-900 mb-2 flex-shrink-0">Market Depth</h3>

                  {/* Chart container */}
                  <div className="flex-1 flex items-end gap-px relative bg-gray-50 rounded-lg p-2">
                    {/* Official line indicator */}
                    <div
                      className="absolute top-0 bottom-0 w-0.5 bg-yellow-500 z-10"
                      style={{
                        left: `${((event.official_spread - event.min_spread) / (event.max_spread - event.min_spread)) * 100}%`
                      }}
                    >
                      <div className="absolute -top-1 left-1/2 -translate-x-1/2 bg-yellow-500 text-white text-xs px-1 rounded">
                        {event.official_spread > 0 ? '+' : ''}{event.official_spread}
                      </div>
                    </div>

                    {chartData.map((d) => {
                      const totalHeightPercent = (d.total / chartMaxVolume) * 100
                      const homeHeightPercent = d.total > 0 ? (d.homeVolume / d.total) * totalHeightPercent : 0
                      const awayHeightPercent = d.total > 0 ? (d.awayVolume / d.total) * totalHeightPercent : 0

                      return (
                        <div
                          key={d.spread}
                          className="flex-1 h-full flex flex-col justify-end cursor-pointer group relative"
                          onClick={() => setSelectedSpread(d.spread)}
                        >
                          {/* Away volume (red, on top) */}
                          <div
                            className={`w-full bg-red-400 hover:bg-red-500 transition-colors ${
                              d.spread === selectedSpread ? 'ring-2 ring-blue-500' : ''
                            }`}
                            style={{ height: `${awayHeightPercent}%`, minHeight: d.awayVolume > 0 ? '2px' : '0' }}
                          />
                          {/* Home volume (green, on bottom) */}
                          <div
                            className={`w-full bg-green-400 hover:bg-green-500 transition-colors ${
                              d.spread === selectedSpread ? 'ring-2 ring-blue-500' : ''
                            }`}
                            style={{ height: `${homeHeightPercent}%`, minHeight: d.homeVolume > 0 ? '2px' : '0' }}
                          />

                          {/* Tooltip on hover */}
                          <div className="absolute bottom-full mb-2 left-1/2 -translate-x-1/2 bg-gray-900 text-white text-xs px-2 py-1 rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap pointer-events-none z-20">
                            {d.spread > 0 ? '+' : ''}{d.spread}: ${d.total.toLocaleString()}
                          </div>
                        </div>
                      )
                    })}
                  </div>

                  {/* X-axis labels */}
                  <div className="flex justify-between mt-1 text-xs text-gray-500 px-2 flex-shrink-0">
                    <span>{event.min_spread}</span>
                    <span>Spread (half-points)</span>
                    <span>+{event.max_spread}</span>
                  </div>

                  {/* Legend */}
                  <div className="flex items-center justify-center gap-6 mt-1 text-xs flex-shrink-0">
                    <div className="flex items-center gap-2">
                      <div className="w-3 h-3 bg-green-400 rounded" />
                      <span className="text-gray-600">{event.home_team}</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="w-3 h-3 bg-red-400 rounded" />
                      <span className="text-gray-600">{event.away_team}</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="w-3 h-0.5 bg-yellow-500" />
                      <span className="text-gray-600">Official Line</span>
                    </div>
                  </div>
                </div>

                {/* Recent Activity Section */}
                <div className="h-48 flex flex-col mt-3 pt-3 border-t flex-shrink-0">
                  <h4 className="font-semibold text-gray-900 mb-2 text-sm flex-shrink-0">
                    Recent Activity ({recentActivity.length} bets)
                  </h4>
                  <div className="flex-1 overflow-y-auto space-y-1">
                    {recentActivity.length > 0 ? (
                      recentActivity.map((bet, i) => (
                        <div key={`${bet.bet_id}-${i}`} className="flex items-center justify-between text-xs py-1.5 px-2 bg-gray-50 rounded hover:bg-gray-100">
                          <span className={`font-medium ${bet.team === 'home' ? 'text-green-600' : 'text-red-600'}`}>
                            {bet.team === 'home' ? event.home_team : event.away_team} {bet.spread > 0 ? '+' : ''}{bet.spread}
                          </span>
                          <span className="text-gray-700 font-mono font-medium">${bet.stake.toFixed(0)}</span>
                          <span className={`px-1.5 py-0.5 rounded text-xs font-medium ${
                            bet.status === 'open' ? 'bg-green-100 text-green-700' :
                            bet.status === 'matched' ? 'bg-yellow-100 text-yellow-700' :
                            'bg-gray-100 text-gray-700'
                          }`}>
                            {bet.status}
                          </span>
                          <span className="text-gray-400">{bet.creator_username}</span>
                        </div>
                      ))
                    ) : (
                      <div className="flex items-center justify-center h-full text-gray-400">
                        No bets yet
                      </div>
                    )}
                  </div>
                </div>
              </div>
            ) : (
              /* Grid View */
              <div className="flex-1 overflow-y-auto">
                <h3 className="font-semibold text-gray-900 mb-4">All Spreads (half-points only)</h3>
                {renderGridView()}
              </div>
            )}
          </div>
        </div>

        {/* Right - Quick Trade Panel */}
        <div className="col-span-3 p-4 bg-gray-50 overflow-y-auto">
          <h3 className="font-semibold text-gray-900 mb-4 flex items-center gap-2">
            <Target size={16} className="text-gray-400" />
            Place Bet
          </h3>

          {!isAuthenticated ? (
            <div className="text-center py-6">
              <p className="text-gray-500 mb-4">Log in to place bets</p>
              <div className="flex gap-2 justify-center">
                <Link to="/login" className="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 text-sm">
                  Log In
                </Link>
                <Link to="/register" className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-sm">
                  Sign Up
                </Link>
              </div>
            </div>
          ) : (
            <>
              {/* Team Selection */}
              <div className="grid grid-cols-2 gap-2 mb-4">
                <button
                  onClick={() => setSelectedSide('home')}
                  className={`py-3 rounded-lg font-semibold transition-all text-sm ${
                    selectedSide === 'home'
                      ? 'bg-green-600 text-white'
                      : 'bg-white border border-gray-300 text-gray-700 hover:bg-gray-50'
                  }`}
                >
                  {event.home_team}
                </button>
                <button
                  onClick={() => setSelectedSide('away')}
                  className={`py-3 rounded-lg font-semibold transition-all text-sm ${
                    selectedSide === 'away'
                      ? 'bg-red-600 text-white'
                      : 'bg-white border border-gray-300 text-gray-700 hover:bg-gray-50'
                  }`}
                >
                  {event.away_team}
                </button>
              </div>

              {/* Spread Selection */}
              <div className="mb-4">
                <label className="text-gray-600 text-xs block mb-1">Spread (half-points only)</label>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => adjustSpread(-1)}
                    className="px-4 py-2 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 font-bold"
                  >
                    −
                  </button>
                  <div className="flex-1 text-center py-2 bg-white border border-gray-300 rounded-lg">
                    <span className="text-xl font-bold text-gray-900">
                      {selectedSpread > 0 ? '+' : ''}{selectedSpread}
                    </span>
                    {selectedSpread === event.official_spread && (
                      <span className="ml-2 text-yellow-600 text-xs">★ Official</span>
                    )}
                  </div>
                  <button
                    onClick={() => adjustSpread(1)}
                    className="px-4 py-2 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 font-bold"
                  >
                    +
                  </button>
                </div>
              </div>

              {/* Stake Amount */}
              <div className="mb-4">
                <label className="text-gray-600 text-xs block mb-1">Stake Amount</label>
                <div className="relative">
                  <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">$</span>
                  <input
                    type="number"
                    value={stakeAmount}
                    onChange={(e) => setStakeAmount(e.target.value)}
                    placeholder={`${event.min_bet_amount} - ${event.max_bet_amount}`}
                    className="w-full bg-white border border-gray-300 rounded-lg py-3 pl-8 pr-4 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>
              </div>

              {/* Quick Stakes */}
              <div className="grid grid-cols-5 gap-1 mb-4">
                {quickStakes.filter(s => s >= event.min_bet_amount && s <= event.max_bet_amount).map(stake => (
                  <button
                    key={stake}
                    onClick={() => setStakeAmount(stake.toString())}
                    className="py-2 text-xs bg-white border border-gray-300 rounded hover:bg-gray-50"
                  >
                    ${stake}
                  </button>
                ))}
              </div>

              {/* Create Bet Button */}
              <button
                onClick={handleCreateBet}
                disabled={createBetMutation.isPending || !stakeAmount}
                className={`w-full py-3 rounded-lg font-bold text-white transition-all mb-3 ${
                  selectedSide === 'home' ? 'bg-green-600 hover:bg-green-700' : 'bg-red-600 hover:bg-red-700'
                } ${(createBetMutation.isPending || !stakeAmount) ? 'opacity-50 cursor-not-allowed' : ''}`}
              >
                {createBetMutation.isPending ? 'Creating...' : `Create ${selectedSide === 'home' ? event.home_team : event.away_team} Bet`}
              </button>

              {/* Available Bets to Take */}
              {availableBets.length > 0 && (
                <div className="border-t pt-4">
                  <h4 className="text-sm font-semibold text-gray-700 mb-2">
                    Take Existing Bet ({availableBets.length} available at {selectedSpread > 0 ? '+' : ''}{selectedSpread})
                  </h4>
                  <div className="space-y-2 max-h-32 overflow-y-auto">
                    {availableBets.map(bet => (
                      <div key={bet.bet_id} className="flex items-center justify-between p-2 bg-white border rounded-lg">
                        <div>
                          <p className={`font-semibold text-sm ${bet.team === 'home' ? 'text-green-600' : 'text-red-600'}`}>
                            ${bet.stake.toFixed(0)} on {bet.team === 'home' ? event.home_team : event.away_team}
                          </p>
                          <p className="text-xs text-gray-500">by {bet.creator_username}</p>
                        </div>
                        <button
                          onClick={() => handleTakeBet(bet.bet_id)}
                          disabled={takeBetMutation.isPending}
                          className="px-3 py-1.5 bg-purple-600 text-white rounded text-sm hover:bg-purple-700 disabled:opacity-50"
                        >
                          Take
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Bet Summary */}
              {stakeAmount && (
                <div className="mt-4 p-3 bg-white border rounded-lg text-xs">
                  <div className="flex justify-between text-gray-600 mb-1">
                    <span>Your Position</span>
                    <span className={selectedSide === 'home' ? 'text-green-600' : 'text-red-600'}>
                      {selectedSide === 'home' ? event.home_team : event.away_team} {selectedSpread > 0 ? '+' : ''}{selectedSide === 'home' ? selectedSpread : -selectedSpread}
                    </span>
                  </div>
                  <div className="flex justify-between text-gray-600 mb-1">
                    <span>Stake</span>
                    <span className="text-gray-900 font-semibold">${parseFloat(stakeAmount).toFixed(2)}</span>
                  </div>
                  <div className="flex justify-between text-gray-600 mb-1">
                    <span>Potential Win</span>
                    <span className="text-green-600 font-semibold">${(parseFloat(stakeAmount) * 0.9 * 2).toFixed(2)}</span>
                  </div>
                  <div className="flex justify-between text-gray-600">
                    <span>House Fee (10%)</span>
                    <span className="text-yellow-600">${(parseFloat(stakeAmount) * 0.1).toFixed(2)}</span>
                  </div>
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  )
}
