import { useState, FormEvent } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { betsApi } from '@/api/bets'
import { Modal } from '@/components/common/Modal'
import { Button } from '@/components/common/Button'
import type { BetCategory } from '@/types'
import { BET_CATEGORIES } from '@/utils/constants'
import { useBlockchainBet } from '@/blockchain/hooks/useBlockchainBet'
import { useGasEstimate } from '@/blockchain/hooks/useGasEstimate'
import { TransactionModal } from '@/blockchain/components/TransactionModal'

interface CreateBetModalProps {
  isOpen: boolean
  onClose: () => void
}

export const CreateBetModal = ({ isOpen, onClose }: CreateBetModalProps) => {
  const queryClient = useQueryClient()
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    category: 'sports' as BetCategory,
    event_name: '',
    creator_position: '',
    opponent_position: '',
    stake_amount: '',
    creator_odds: '1',
    opponent_odds: '1',
  })

  // Blockchain integration
  const { createBet: createBlockchainBet, txStatus, txHash } = useBlockchainBet()
  const gasEstimate = useGasEstimate(
    'create_bet',
    { stakeAmount: parseFloat(formData.stake_amount) || 0 }
  )

  const createMutation = useMutation({
    mutationFn: betsApi.createBet,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['bets'] })
      onClose()
      setFormData({
        title: '',
        description: '',
        category: 'sports',
        event_name: '',
        creator_position: '',
        opponent_position: '',
        stake_amount: '',
        creator_odds: '1',
        opponent_odds: '1',
      })
    },
  })

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

    const betData = {
      ...formData,
      stake_amount: parseFloat(formData.stake_amount),
      creator_odds: parseFloat(formData.creator_odds),
      opponent_odds: parseFloat(formData.opponent_odds),
    }

    // Create bet with blockchain integration
    // This will: 1) Create in backend, 2) Sign transaction, 3) Update with blockchain ID
    try {
      await createBlockchainBet(betData)
      queryClient.invalidateQueries({ queryKey: ['bets'] })
      onClose()
      setFormData({
        title: '',
        description: '',
        category: 'sports',
        event_name: '',
        creator_position: '',
        opponent_position: '',
        stake_amount: '',
        creator_odds: '1',
        opponent_odds: '1',
      })
    } catch (error) {
      console.error('Failed to create bet:', error)
    }
  }

  return (
    <Modal isOpen={isOpen} onClose={onClose} title="Create New Bet">
      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Title
          </label>
          <input
            type="text"
            value={formData.title}
            onChange={(e) => setFormData({ ...formData, title: e.target.value })}
            required
            maxLength={200}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Description
          </label>
          <textarea
            value={formData.description}
            onChange={(e) => setFormData({ ...formData, description: e.target.value })}
            required
            rows={3}
            maxLength={2000}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Category
            </label>
            <select
              value={formData.category}
              onChange={(e) => setFormData({ ...formData, category: e.target.value as BetCategory })}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
            >
              {Object.entries(BET_CATEGORIES).map(([value, label]) => (
                <option key={value} value={value}>{label}</option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Event Name
            </label>
            <input
              type="text"
              value={formData.event_name}
              onChange={(e) => setFormData({ ...formData, event_name: e.target.value })}
              required
              maxLength={200}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
            />
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Your Position
          </label>
          <input
            type="text"
            value={formData.creator_position}
            onChange={(e) => setFormData({ ...formData, creator_position: e.target.value })}
            required
            maxLength={500}
            placeholder="What are you betting on?"
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Opponent Position
          </label>
          <input
            type="text"
            value={formData.opponent_position}
            onChange={(e) => setFormData({ ...formData, opponent_position: e.target.value })}
            required
            maxLength={500}
            placeholder="What is the opposing position?"
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </div>

        <div className="grid grid-cols-3 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Stake Amount ($)
            </label>
            <input
              type="number"
              value={formData.stake_amount}
              onChange={(e) => setFormData({ ...formData, stake_amount: e.target.value })}
              required
              min="0.01"
              max="10000"
              step="0.01"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Your Odds
            </label>
            <input
              type="number"
              value={formData.creator_odds}
              onChange={(e) => setFormData({ ...formData, creator_odds: e.target.value })}
              min="0.01"
              step="0.1"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Opponent Odds
            </label>
            <input
              type="number"
              value={formData.opponent_odds}
              onChange={(e) => setFormData({ ...formData, opponent_odds: e.target.value })}
              min="0.01"
              step="0.1"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
            />
          </div>
        </div>

        {/* Gas Estimate */}
        {formData.stake_amount && parseFloat(formData.stake_amount) > 0 && (
          <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
            <div className="text-xs font-medium text-blue-800 mb-1">Estimated Gas Cost</div>
            {gasEstimate.isLoading ? (
              <div className="text-sm text-blue-600">Calculating...</div>
            ) : gasEstimate.error ? (
              <div className="text-sm text-red-600">{gasEstimate.error}</div>
            ) : (
              <div className="flex items-center justify-between text-sm">
                <span className="text-blue-900">{gasEstimate.costEth} ETH</span>
                <span className="text-blue-700">≈ ${gasEstimate.costUsd}</span>
              </div>
            )}
          </div>
        )}

        <div className="flex gap-4 pt-4">
          <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
            Cancel
          </Button>
          <Button type="submit" className="flex-1" disabled={txStatus === 'pending' || txStatus === 'confirming'}>
            {txStatus === 'pending' || txStatus === 'confirming' ? 'Processing...' : 'Create Bet'}
          </Button>
        </div>
      </form>

      {/* Transaction Status Modal */}
      <TransactionModal
        isOpen={txStatus !== 'idle'}
        status={txStatus}
        txHash={txHash}
        message={
          txStatus === 'success'
            ? 'Your bet has been created on the blockchain!'
            : txStatus === 'error'
            ? 'Failed to create bet on blockchain'
            : undefined
        }
        onClose={() => {}}
        autoCloseOnSuccess={true}
        autoCloseDelay={2000}
      />
    </Modal>
  )
}
