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

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

export const CreateSpreadBetModal = ({
  isOpen,
  onClose,
  event,
  spread,
}: CreateSpreadBetModalProps) => {
  const [stakeAmount, setStakeAmount] = useState('')
  const queryClient = useQueryClient()

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

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()

    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
    }

    // Determine which team based on spread sign
    // Positive spread = home team underdog, negative spread = home team favorite
    const team = spread >= 0 ? TeamSide.HOME : TeamSide.AWAY

    createBetMutation.mutate({
      event_id: event.id,
      spread: Math.abs(spread),
      team,
      stake_amount: amount,
    })
  }

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

  const interpretation = interpretSpread()

  return (
    <Modal isOpen={isOpen} onClose={onClose} title="Create Spread Bet">
      <form onSubmit={handleSubmit} className="space-y-4">
        <div className="bg-blue-50 p-4 rounded-lg">
          <h3 className="font-semibold text-gray-900 mb-2">Your Bet</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>
        </div>

        <div className="bg-gray-50 p-4 rounded-lg">
          <h4 className="font-semibold text-gray-900 mb-2">How it works</h4>
          <ul className="text-sm text-gray-600 space-y-1">
            <li>• You stake your chosen amount</li>
            <li>• Another user takes the opposite side with equal stake</li>
            <li>• House takes 10% commission from the pot</li>
            <li>• Winner receives remaining 90%</li>
          </ul>
        </div>

        <Input
          label="Stake Amount"
          type="number"
          step="0.01"
          min={event.min_bet_amount}
          max={event.max_bet_amount}
          value={stakeAmount}
          onChange={(e) => setStakeAmount(e.target.value)}
          placeholder={`$${event.min_bet_amount} - $${event.max_bet_amount}`}
          required
        />

        <div className="text-sm text-gray-600">
          <p>
            Min: ${event.min_bet_amount} | Max: ${event.max_bet_amount}
          </p>
          {stakeAmount && !isNaN(parseFloat(stakeAmount)) && (
            <p className="mt-2 font-semibold text-gray-900">
              Potential Payout: $
              {(parseFloat(stakeAmount) * 2 * 0.9).toFixed(2)} (90% of $
              {(parseFloat(stakeAmount) * 2).toFixed(2)} pot)
            </p>
          )}
        </div>

        <div className="flex gap-3 pt-4">
          <Button
            type="button"
            variant="secondary"
            onClick={onClose}
            disabled={createBetMutation.isPending}
            className="flex-1"
          >
            Cancel
          </Button>
          <Button
            type="submit"
            disabled={createBetMutation.isPending}
            className="flex-1"
          >
            {createBetMutation.isPending ? 'Creating...' : 'Create Bet'}
          </Button>
        </div>
      </form>
    </Modal>
  )
}
