import { useMutation, useQueryClient } from '@tanstack/react-query'
import { Modal } from '@/components/common/Modal'
import { Button } from '@/components/common/Button'
import { spreadBetsApi } from '@/api/spread-bets'
import type { SportEventWithBets } from '@/types/sport-event'
import { toast } from 'react-hot-toast'

interface TakeBetModalProps {
  isOpen: boolean
  onClose: () => void
  betId: number
  spread: number
  event: SportEventWithBets
}

export const TakeBetModal = ({
  isOpen,
  onClose,
  betId,
  spread,
  event,
}: TakeBetModalProps) => {
  const queryClient = useQueryClient()
  // spread_grid returns an array of bets at this spread - find the specific bet by ID
  const betsAtSpread = event.spread_grid[spread.toString()] || []
  const betInfo = betsAtSpread.find(b => b.bet_id === betId)

  const takeBetMutation = useMutation({
    mutationFn: () => spreadBetsApi.takeBet(betId),
    onSuccess: () => {
      toast.success('Bet taken successfully!')
      queryClient.invalidateQueries({ queryKey: ['sport-event', event.id] })
      queryClient.invalidateQueries({ queryKey: ['my-spread-bets'] })
      onClose()
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.detail || 'Failed to take bet')
    },
  })

  if (!betInfo) return null

  const handleTakeBet = () => {
    takeBetMutation.mutate()
  }

  const getOppositeInterpretation = () => {
    if (spread === 0) {
      return {
        team: event.away_team,
        description: 'Pick Em - must win outright',
      }
    } else if (spread > 0) {
      // Creator has home team +spread, taker gets away team -spread
      return {
        team: event.away_team,
        description: `must win by more than ${spread} points`,
      }
    } else {
      // Creator has away team -spread, taker gets home team +spread
      return {
        team: event.home_team,
        description: `can lose by up to ${Math.abs(spread) - 0.5} points and still win`,
      }
    }
  }

  const interpretation = getOppositeInterpretation()

  return (
    <Modal isOpen={isOpen} onClose={onClose} title="Take Bet">
      <div className="space-y-4">
        <div className="bg-gray-50 p-4 rounded-lg">
          <h3 className="font-semibold text-gray-900 mb-2">Their Bet</h3>
          <p className="text-sm text-gray-700">
            <strong>{betInfo.creator_username}</strong> is betting{' '}
            <strong>${betInfo.stake}</strong> on{' '}
            <strong>
              {spread >= 0 ? event.home_team : event.away_team} {spread > 0 ? '+' : ''}
              {spread}
            </strong>
          </p>
        </div>

        <div className="bg-blue-50 p-4 rounded-lg">
          <h3 className="font-semibold text-gray-900 mb-2">Your Bet (Opposite Side)</h3>
          <p className="text-sm text-gray-700">
            <strong>{interpretation.team}</strong> {-spread > 0 ? '+' : ''}
            {-spread}
          </p>
          <p className="text-xs text-gray-600 mt-1">{interpretation.description}</p>
          <p className="text-sm font-semibold text-gray-900 mt-2">
            Your stake: ${betInfo.stake}
          </p>
        </div>

        <div className="bg-yellow-50 p-4 rounded-lg border border-yellow-200">
          <h4 className="font-semibold text-gray-900 mb-2">Payout Details</h4>
          <div className="text-sm text-gray-700 space-y-1">
            <p>Total pot: ${(betInfo.stake * 2).toFixed(2)}</p>
            <p>House commission (10%): ${(betInfo.stake * 2 * 0.1).toFixed(2)}</p>
            <p className="font-bold text-green-600">
              Winner receives: ${(betInfo.stake * 2 * 0.9).toFixed(2)}
            </p>
          </div>
        </div>

        <div className="bg-red-50 p-3 rounded-lg border border-red-200">
          <p className="text-sm text-red-800">
            ⚠️ By taking this bet, <strong>${betInfo.stake}</strong> will be locked from
            your wallet until the event is settled.
          </p>
        </div>

        <div className="flex gap-3 pt-4">
          <Button
            type="button"
            variant="secondary"
            onClick={onClose}
            disabled={takeBetMutation.isPending}
            className="flex-1"
          >
            Cancel
          </Button>
          <Button
            onClick={handleTakeBet}
            disabled={takeBetMutation.isPending}
            className="flex-1"
          >
            {takeBetMutation.isPending ? 'Taking Bet...' : `Take Bet ($${betInfo.stake})`}
          </Button>
        </div>
      </div>
    </Modal>
  )
}
