import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Layout } from '@/components/layout/Layout'
import { Loading } from '@/components/common/Loading'
import { spreadBetsApi } from '@/api/spread-bets'
import type { SpreadBetDetail } from '@/types/spread-bet'

const SpreadBetCard = ({ bet }: { bet: SpreadBetDetail }) => {
  const isCreator = bet.creator_username !== undefined
  const statusColors = {
    open: 'bg-blue-100 text-blue-800',
    matched: 'bg-yellow-100 text-yellow-800',
    completed: 'bg-green-100 text-green-800',
    cancelled: 'bg-gray-100 text-gray-800',
  }

  return (
    <div className="bg-white p-6 rounded-lg shadow">
      <div className="flex justify-between items-start mb-4">
        <div>
          <h3 className="text-lg font-semibold text-gray-900">
            {bet.event_home_team} vs {bet.event_away_team}
          </h3>
          <p className="text-sm text-gray-500">
            {new Date(bet.event_game_time).toLocaleString()}
          </p>
        </div>
        <span className={`px-3 py-1 rounded-full text-sm font-medium ${statusColors[bet.status] || statusColors.open}`}>
          {bet.status.charAt(0).toUpperCase() + bet.status.slice(1)}
        </span>
      </div>

      <div className="grid grid-cols-2 gap-4 mb-4">
        <div>
          <p className="text-sm text-gray-500">Your Spread</p>
          <p className="text-xl font-bold text-gray-900">
            {bet.spread > 0 ? '+' : ''}{bet.spread}
          </p>
        </div>
        <div>
          <p className="text-sm text-gray-500">Stake</p>
          <p className="text-xl font-bold text-green-600">${Number(bet.stake_amount).toFixed(2)}</p>
        </div>
      </div>

      <div className="border-t pt-4">
        <div className="flex justify-between text-sm">
          <div>
            <span className="text-gray-500">Team: </span>
            <span className="font-medium">{bet.team === 'home' ? bet.event_home_team : bet.event_away_team}</span>
          </div>
          <div>
            <span className="text-gray-500">Official Line: </span>
            <span className="font-medium">{bet.event_official_spread > 0 ? '+' : ''}{bet.event_official_spread}</span>
          </div>
        </div>
        {bet.taker_username && (
          <div className="mt-2 text-sm">
            <span className="text-gray-500">Opponent: </span>
            <span className="font-medium">{bet.taker_username}</span>
          </div>
        )}
      </div>
    </div>
  )
}

export const MyBets = () => {
  const [activeTab, setActiveTab] = useState<'active' | 'history'>('active')

  const { data: activeBets, isLoading: activeLoading } = useQuery({
    queryKey: ['myActiveSpreadBets'],
    queryFn: spreadBetsApi.getMyActiveBets,
    enabled: activeTab === 'active',
  })

  // For history, we could add a separate endpoint later
  // For now, just show active bets
  const currentBets = activeTab === 'active' ? activeBets : []

  return (
    <Layout>
      <div className="space-y-6">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">My Bets</h1>
          <p className="text-gray-600 mt-2">View and manage your spread bets</p>
        </div>

        <div className="flex gap-2 border-b">
          {[
            { key: 'active' as const, label: 'Active Bets' },
            { key: 'history' as const, label: 'History' },
          ].map(({ key, label }) => (
            <button
              key={key}
              onClick={() => setActiveTab(key)}
              className={`px-6 py-3 font-medium transition-colors ${
                activeTab === key
                  ? 'text-primary border-b-2 border-primary'
                  : 'text-gray-600 hover:text-gray-900'
              }`}
            >
              {label}
            </button>
          ))}
        </div>

        {activeLoading ? (
          <Loading />
        ) : currentBets && currentBets.length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {currentBets.map((bet) => (
              <SpreadBetCard key={bet.id} bet={bet} />
            ))}
          </div>
        ) : (
          <div className="text-center py-12">
            <p className="text-gray-500 text-lg">No bets found</p>
            <p className="text-gray-400 mt-2">
              {activeTab === 'active'
                ? 'Create a bet on the Sport Events page to get started!'
                : 'Your completed bets will appear here'}
            </p>
          </div>
        )}
      </div>
    </Layout>
  )
}
