import { useState, useEffect } from 'react'
import { Box, Typography, Chip, CircularProgress, Tooltip, Fade } from '@mui/material'
import { TrendingUp, TrendingDown } from '@mui/icons-material'
import { useQuery } from '@tanstack/react-query'
import { marketDataApi, TickerData } from '../api/marketData'
import { useWebSocketContext } from './WebSocketProvider'

interface RealtimePriceProps {
  symbol: string
  showProvider?: boolean
  showChange?: boolean
  size?: 'small' | 'medium' | 'large'
  onPriceUpdate?: (price: number) => void
}

export default function RealtimePrice({
  symbol,
  showProvider = true,
  showChange = true,
  size = 'medium',
  onPriceUpdate,
}: RealtimePriceProps) {
  const { isConnected, lastMessage } = useWebSocketContext()
  const [currentPrice, setCurrentPrice] = useState<number | null>(null)
  const [previousPrice, setPreviousPrice] = useState<number | null>(null)
  const [priceChange, setPriceChange] = useState<number>(0)
  const [flash, setFlash] = useState(false)

  const { data: ticker, isLoading, error, refetch } = useQuery({
    queryKey: ['ticker', symbol],
    queryFn: () => marketDataApi.getTicker(symbol),
    refetchInterval: 5000, // Refetch every 5 seconds as fallback
    enabled: !!symbol,
  })

  // Update price when ticker data changes
  useEffect(() => {
    // Only update if we have a valid price (including 0, but not null/undefined)
    if (ticker?.last !== undefined && ticker?.last !== null) {
      const newPrice = ticker.last

      setCurrentPrice((prevPrice) => {
        // Check if price has changed
        if (prevPrice !== null && newPrice !== prevPrice) {
          setPreviousPrice(prevPrice)
          setPriceChange(newPrice - prevPrice)

          // Flash animation
          setFlash(true)
          setTimeout(() => setFlash(false), 2000)

          // Call callback if provided
          if (onPriceUpdate) {
            onPriceUpdate(newPrice)
          }
        }

        // Always update currentPrice when we have valid ticker data
        // This ensures the price persists even if ticker becomes undefined later
        return newPrice
      })
    }
  }, [ticker?.last, onPriceUpdate])

  // Listen for WebSocket price updates
  useEffect(() => {
    if (!isConnected || !lastMessage) return

    try {
      const message = typeof lastMessage === 'string' ? JSON.parse(lastMessage) : lastMessage

      if (message.type === 'price_update' && message.symbol === symbol && message.price !== undefined && message.price !== null) {
        const newPrice = parseFloat(message.price)

        // Validate the parsed price
        if (isNaN(newPrice)) return

        setCurrentPrice((prevPrice) => {
          if (prevPrice !== null && newPrice !== prevPrice) {
            setPreviousPrice(prevPrice)
            setPriceChange(newPrice - prevPrice)

            // Flash animation
            setFlash(true)
            setTimeout(() => setFlash(false), 2000)

            if (onPriceUpdate) {
              onPriceUpdate(newPrice)
            }
          }

          return newPrice
        })
      }
    } catch (e) {
      // Ignore parsing errors
    }
  }, [isConnected, lastMessage, symbol, onPriceUpdate])

  if (isLoading && currentPrice === null) {
    return (
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <CircularProgress size={size === 'small' ? 16 : size === 'large' ? 24 : 20} />
        <Typography variant={size === 'small' ? 'body2' : size === 'large' ? 'h6' : 'body1'}>
          Loading...
        </Typography>
      </Box>
    )
  }

  if (error) {
    return (
      <Typography variant={size === 'small' ? 'body2' : 'body1'} color="error">
        Error loading price
      </Typography>
    )
  }

  // Use currentPrice if available, otherwise fall back to ticker?.last
  // Only show 0 if both are explicitly 0 (not null/undefined)
  const price = currentPrice !== null ? currentPrice : (ticker?.last !== undefined && ticker?.last !== null ? ticker.last : null)
  const isPositive = priceChange >= 0
  const changePercent = currentPrice !== null && previousPrice !== null ? ((priceChange / previousPrice) * 100).toFixed(2) : null

  const priceVariant = size === 'small' ? 'body2' : size === 'large' ? 'h5' : 'h6'
  const priceColor = flash ? (isPositive ? 'success.main' : 'error.main') : 'text.primary'

  // Don't render price if we don't have a valid price value
  if (price === null) {
    return (
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <CircularProgress size={size === 'small' ? 16 : size === 'large' ? 24 : 20} />
        <Typography variant={size === 'small' ? 'body2' : size === 'large' ? 'h6' : 'body1'}>
          Loading price...
        </Typography>
      </Box>
    )
  }

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
        <Typography
          variant={priceVariant}
          sx={{
            color: priceColor,
            fontWeight: 600,
            transition: 'color 0.3s',
          }}
        >
          ${price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 8 })}
        </Typography>

        {showChange && changePercent && (
          <Chip
            icon={isPositive ? <TrendingUp /> : <TrendingDown />}
            label={`${isPositive ? '+' : ''}${changePercent}%`}
            color={isPositive ? 'success' : 'error'}
            size="small"
            variant="outlined"
          />
        )}

        {showProvider && ticker?.provider && (
          <Tooltip title={`Data provider: ${ticker.provider}`}>
            <Chip label={ticker.provider} size="small" variant="outlined" color="default" />
          </Tooltip>
        )}
      </Box>

      {ticker && (
        <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
          <Typography variant="caption" color="text.secondary">
            24h: ${ticker.high.toFixed(2)} / ${ticker.low.toFixed(2)}
          </Typography>
          {ticker.volume > 0 && (
            <Typography variant="caption" color="text.secondary">
              Vol: ${ticker.volume.toLocaleString('en-US', { maximumFractionDigits: 0 })}
            </Typography>
          )}
        </Box>
      )}
    </Box>
  )
}
