import { useParams, useNavigate } from 'react-router-dom'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Layout } from '@/components/layout/Layout'
import { Card } from '@/components/common/Card'
import { Button } from '@/components/common/Button'
import { Loading } from '@/components/common/Loading'
import { betsApi } from '@/api/bets'
import { useAuthStore } from '@/store'
import { formatCurrency, formatDateTime } from '@/utils/formatters'
import { BET_CATEGORIES, BET_STATUS_COLORS } from '@/utils/constants'
import { Calendar, User, DollarSign, TrendingUp } from 'lucide-react'
import { useBlockchainBet } from '@/blockchain/hooks/useBlockchainBet'
import { useGasEstimate } from '@/blockchain/hooks/useGasEstimate'
import { BlockchainBadge } from '@/blockchain/components/BlockchainBadge'
import { TransactionModal } from '@/blockchain/components/TransactionModal'

export const BetDetails = () => {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const { user } = useAuthStore()
  const queryClient = useQueryClient()

  const { data: bet, isLoading } = useQuery({
    queryKey: ['bet', id],
    queryFn: () => betsApi.getBet(Number(id)),
  })

  // Blockchain integration
  const { acceptBet: acceptBlockchainBet, txStatus, txHash } = useBlockchainBet()
  const gasEstimate = useGasEstimate('accept_bet', { stakeAmount: bet?.stake_amount || 0 })

  const acceptMutation = useMutation({
    mutationFn: () => betsApi.acceptBet(Number(id)),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['bet', id] })
      queryClient.invalidateQueries({ queryKey: ['bets'] })
      queryClient.invalidateQueries({ queryKey: ['wallet'] })
    },
  })

  const settleMutation = useMutation({
    mutationFn: (winnerId: number) => betsApi.settleBet(Number(id), winnerId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['bet', id] })
      queryClient.invalidateQueries({ queryKey: ['wallet'] })
    },
  })

  if (isLoading) return <Layout><Loading /></Layout>
  if (!bet) return <Layout><div>Bet not found</div></Layout>

  const isCreator = user?.id === bet.creator.id
  const isOpponent = user?.id === bet.opponent?.id
  const isParticipant = isCreator || isOpponent
  const canAccept = bet.status === 'open' && !isCreator
  const canSettle = bet.status === 'matched' && isParticipant

  return (
    <Layout>
      <div className="max-w-4xl mx-auto space-y-6">
        <Button variant="secondary" onClick={() => navigate(-1)}>
          ← Back
        </Button>

        <Card>
          <div className="space-y-6">
            <div className="flex justify-between items-start">
              <div>
                <h1 className="text-3xl font-bold text-gray-900 mb-2">{bet.title}</h1>
                <div className="flex items-center gap-3 text-sm text-gray-600">
                  <span className="px-2 py-0.5 bg-gray-100 rounded">
                    {BET_CATEGORIES[bet.category]}
                  </span>
                  <span className={`px-2 py-1 rounded text-xs font-medium ${BET_STATUS_COLORS[bet.status]}`}>
                    {bet.status}
                  </span>
                  {bet.blockchain_tx_hash && (
                    <BlockchainBadge
                      status="confirmed"
                      txHash={bet.blockchain_tx_hash}
                    />
                  )}
                </div>
              </div>
            </div>

            <p className="text-gray-700 text-lg">{bet.description}</p>

            <div className="grid md:grid-cols-2 gap-6 pt-6 border-t">
              <div className="space-y-4">
                <h3 className="font-semibold text-lg">Bet Details</h3>

                <div className="flex items-center gap-3">
                  <Calendar size={20} className="text-gray-400" />
                  <div>
                    <p className="text-sm text-gray-600">Event</p>
                    <p className="font-medium">{bet.event_name}</p>
                  </div>
                </div>

                {bet.event_date && (
                  <div className="flex items-center gap-3">
                    <Calendar size={20} className="text-gray-400" />
                    <div>
                      <p className="text-sm text-gray-600">Event Date</p>
                      <p className="font-medium">{formatDateTime(bet.event_date)}</p>
                    </div>
                  </div>
                )}

                <div className="flex items-center gap-3">
                  <DollarSign size={20} className="text-gray-400" />
                  <div>
                    <p className="text-sm text-gray-600">Stake Amount</p>
                    <p className="font-medium text-xl text-primary">{formatCurrency(bet.stake_amount)}</p>
                  </div>
                </div>

                <div className="flex items-center gap-3">
                  <TrendingUp size={20} className="text-gray-400" />
                  <div>
                    <p className="text-sm text-gray-600">Odds</p>
                    <p className="font-medium">{bet.creator_odds}x / {bet.opponent_odds}x</p>
                  </div>
                </div>
              </div>

              <div className="space-y-4">
                <h3 className="font-semibold text-lg">Participants</h3>

                <div className="flex items-center gap-3">
                  <User size={20} className="text-gray-400" />
                  <div>
                    <p className="text-sm text-gray-600">Creator</p>
                    <p className="font-medium">{bet.creator.display_name || bet.creator.username}</p>
                    <p className="text-sm text-gray-600 mt-1">Position: {bet.creator_position}</p>
                  </div>
                </div>

                <div className="flex items-center gap-3">
                  <User size={20} className="text-gray-400" />
                  <div>
                    <p className="text-sm text-gray-600">Opponent</p>
                    {bet.opponent ? (
                      <>
                        <p className="font-medium">{bet.opponent.display_name || bet.opponent.username}</p>
                        <p className="text-sm text-gray-600 mt-1">Position: {bet.opponent_position}</p>
                      </>
                    ) : (
                      <p className="font-medium text-gray-400">Waiting for opponent...</p>
                    )}
                  </div>
                </div>
              </div>
            </div>

            {canAccept && (
              <div className="pt-6 border-t space-y-4">
                {/* Gas Estimate */}
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                  <div className="text-sm font-medium text-blue-800 mb-2">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">
                      <span className="text-blue-900 font-medium">{gasEstimate.costEth} ETH</span>
                      <span className="text-blue-700">≈ ${gasEstimate.costUsd}</span>
                    </div>
                  )}
                </div>

                <Button
                  onClick={async () => {
                    try {
                      await acceptBlockchainBet(Number(id), bet.stake_amount)
                      queryClient.invalidateQueries({ queryKey: ['bet', id] })
                      queryClient.invalidateQueries({ queryKey: ['bets'] })
                      queryClient.invalidateQueries({ queryKey: ['wallet'] })
                    } catch (error) {
                      console.error('Failed to accept bet:', error)
                    }
                  }}
                  disabled={txStatus === 'pending' || txStatus === 'confirming'}
                  className="w-full"
                >
                  {txStatus === 'pending' || txStatus === 'confirming'
                    ? 'Processing...'
                    : `Accept Bet - ${formatCurrency(bet.stake_amount)}`}
                </Button>
              </div>
            )}

            {canSettle && (
              <div className="pt-6 border-t space-y-4">
                <h3 className="font-semibold">Settle Bet</h3>
                <div className="flex gap-4">
                  <Button
                    onClick={() => settleMutation.mutate(bet.creator.id)}
                    disabled={settleMutation.isPending}
                    className="flex-1"
                  >
                    {bet.creator.display_name || bet.creator.username} Won
                  </Button>
                  <Button
                    onClick={() => settleMutation.mutate(bet.opponent!.id)}
                    disabled={settleMutation.isPending}
                    className="flex-1"
                  >
                    {bet.opponent?.display_name || bet.opponent?.username} Won
                  </Button>
                </div>
              </div>
            )}
          </div>
        </Card>
      </div>

      {/* Transaction Status Modal */}
      <TransactionModal
        isOpen={txStatus !== 'idle'}
        status={txStatus}
        txHash={txHash}
        message={
          txStatus === 'success'
            ? 'Bet accepted successfully on blockchain!'
            : txStatus === 'error'
            ? 'Failed to accept bet on blockchain'
            : undefined
        }
        onClose={() => {}}
        autoCloseOnSuccess={true}
        autoCloseDelay={2000}
      />
    </Layout>
  )
}
