import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Layout } from '@/components/layout/Layout'
import { Loading } from '@/components/common/Loading'
import { Button } from '@/components/common/Button'
import { sportEventsApi } from '@/api/sport-events'
import { SpreadGrid } from '@/components/bets/SpreadGrid'
import { ChevronLeft } from 'lucide-react'

export const SportEvents = () => {
  const [selectedEventId, setSelectedEventId] = useState<number | null>(null)

  const { data: events, isLoading: isLoadingEvents } = useQuery({
    queryKey: ['sport-events'],
    queryFn: () => sportEventsApi.getUpcomingEvents(),
  })

  const { data: selectedEvent, isLoading: isLoadingEvent } = useQuery({
    queryKey: ['sport-event', selectedEventId],
    queryFn: () => sportEventsApi.getEventWithGrid(selectedEventId!),
    enabled: selectedEventId !== null,
  })

  const handleEventClick = (eventId: number) => {
    setSelectedEventId(eventId)
  }

  const handleBackToList = () => {
    setSelectedEventId(null)
  }

  if (isLoadingEvents) {
    return (
      <Layout>
        <Loading />
      </Layout>
    )
  }

  if (selectedEventId && isLoadingEvent) {
    return (
      <Layout>
        <div className="space-y-4">
          <Button variant="secondary" onClick={handleBackToList}>
            
            Back to Events
          </Button>
          <Loading />
        </div>
      </Layout>
    )
  }

  return (
    <Layout>
      <div className="space-y-6">
        {selectedEvent ? (
          <>
            <Button variant="secondary" onClick={handleBackToList}>
              
              Back to Events
            </Button>
            <SpreadGrid
              event={selectedEvent}
              onBetCreated={() => {
                // Refetch to update grid
              }}
              onBetTaken={() => {
                // Refetch to update grid
              }}
            />
          </>
        ) : (
          <>
            <div>
              <h1 className="text-3xl font-bold text-gray-900">Sport Events</h1>
              <p className="text-gray-600 mt-2">
                Browse upcoming events and place spread bets
              </p>
            </div>

            {!events || events.length === 0 ? (
              <div className="text-center py-12 bg-white rounded-lg shadow">
                <p className="text-gray-600">No upcoming events available</p>
              </div>
            ) : (
              <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                {events.map((event) => {
                  const gameTime = new Date(event.game_time)
                  const now = new Date()
                  const hoursUntil = Math.floor(
                    (gameTime.getTime() - now.getTime()) / (1000 * 60 * 60)
                  )

                  return (
                    <button
                      key={event.id}
                      onClick={() => handleEventClick(event.id)}
                      className="bg-white p-6 rounded-lg shadow hover:shadow-lg transition-shadow text-left"
                    >
                      <div className="flex justify-between items-start mb-3">
                        <div className="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-xs font-semibold uppercase">
                          {event.sport}
                        </div>
                        {hoursUntil < 24 && hoursUntil >= 0 && (
                          <div className="px-2 py-1 bg-red-100 text-red-800 rounded text-xs font-semibold">
                            {hoursUntil}h
                          </div>
                        )}
                      </div>

                      <h3 className="font-bold text-lg text-gray-900 mb-2">
                        {event.home_team} vs {event.away_team}
                      </h3>

                      <div className="space-y-1 text-sm text-gray-600">
                        <p>
                          <strong>Spread:</strong> {event.home_team}{' '}
                          {event.official_spread > 0 ? '+' : ''}
                          {event.official_spread}
                        </p>
                        <p>
                          <strong>Time:</strong> {gameTime.toLocaleString()}
                        </p>
                        {event.venue && (
                          <p>
                            <strong>Venue:</strong> {event.venue}
                          </p>
                        )}
                        {event.league && (
                          <p className="text-xs text-gray-500">{event.league}</p>
                        )}
                      </div>

                      <div className="mt-4 pt-4 border-t border-gray-200">
                        <p className="text-xs text-gray-500">
                          Bet range: ${event.min_bet_amount} - ${event.max_bet_amount}
                        </p>
                        <p className="text-xs text-gray-500">
                          Spread range: {event.min_spread} to {event.max_spread}
                        </p>
                      </div>
                    </button>
                  )
                })}
              </div>
            )}
          </>
        )}
      </div>
    </Layout>
  )
}
