import { useEffect, useRef, useState } from "react";
import { useTicker } from "../../hooks/useTicker";
import { formatPrice, formatPercent, formatVolume } from "../../lib/utils";

interface TickerPriceProps {
  symbol: string;
  show24hChange?: boolean;
  showVolume?: boolean;
  size?: "sm" | "md" | "lg";
  className?: string;
}

type PriceDirection = "up" | "down" | "neutral";

export function TickerPrice({
  symbol,
  show24hChange = true,
  showVolume = true,
  size = "md",
  className = "",
}: TickerPriceProps) {
  const { ticker, isConnected } = useTicker(symbol);
  const [priceDirection, setPriceDirection] =
    useState<PriceDirection>("neutral");
  const [isAnimating, setIsAnimating] = useState(false);
  const prevPriceRef = useRef<number | null>(null);

  // Handle price change animation
  useEffect(() => {
    if (!ticker) return;

    const currentPrice = ticker.lastPrice;
    const prevPrice = prevPriceRef.current;

    if (prevPrice !== null && currentPrice !== prevPrice) {
      const direction = currentPrice > prevPrice ? "up" : "down";
      setPriceDirection(direction);
      setIsAnimating(true);

      // Reset animation after 500ms
      const timer = setTimeout(() => {
        setIsAnimating(false);
      }, 500);

      return () => clearTimeout(timer);
    }
  }, [ticker?.lastPrice]);

  // Update prevPriceRef after render
  useEffect(() => {
    if (ticker) {
      prevPriceRef.current = ticker.lastPrice;
    }
  }, [ticker?.lastPrice]);

  // Size classes
  const sizeClasses = {
    sm: {
      price: "text-lg font-semibold",
      change: "text-xs",
      volume: "text-xs",
      label: "text-xs text-gray-500",
    },
    md: {
      price: "text-2xl font-bold",
      change: "text-sm",
      volume: "text-sm",
      label: "text-xs text-gray-500",
    },
    lg: {
      price: "text-4xl font-bold",
      change: "text-base",
      volume: "text-base",
      label: "text-sm text-gray-500",
    },
  };

  const classes = sizeClasses[size];

  // Get color based on price change direction
  const getPriceColor = () => {
    if (!ticker) return "text-gray-900";
    if (isAnimating) {
      return priceDirection === "up"
        ? "text-green-600 animate-pulse"
        : "text-red-600 animate-pulse";
    }
    return ticker.priceChangePercent >= 0 ? "text-green-600" : "text-red-600";
  };

  // Get change icon
  const getChangeIcon = () => {
    if (!ticker) return null;
    return ticker.priceChangePercent >= 0 ? "📈" : "📉";
  };

  if (!ticker) {
    return (
      <div className={`flex flex-col gap-1 ${className}`}>
        <span className={classes.price}>--</span>
        {!isConnected && (
          <span className="text-xs text-gray-400">连接中...</span>
        )}
      </div>
    );
  }

  return (
    <div className={`flex flex-col gap-1 ${className}`}>
      {/* Price */}
      <div className="flex items-center gap-2">
        <span
          className={`${classes.price} ${getPriceColor()} transition-colors duration-300`}
        >
          {formatPrice(ticker.lastPrice)}
        </span>
        {isAnimating && (
          <span className="text-xs animate-bounce">
            {priceDirection === "up" ? "▲" : "▼"}
          </span>
        )}
      </div>

      {/* 24h Change */}
      {show24hChange && (
        <div className={`flex items-center gap-1 ${classes.change}`}>
          <span>{getChangeIcon()}</span>
          <span
            className={
              ticker.priceChangePercent >= 0 ? "text-green-600" : "text-red-600"
            }
          >
            {ticker.priceChangePercent >= 0 ? "+" : ""}
            {formatPercent(ticker.priceChangePercent)}
          </span>
          <span className="text-gray-400">|</span>
          <span
            className={
              ticker.priceChange >= 0 ? "text-green-600" : "text-red-600"
            }
          >
            {ticker.priceChange >= 0 ? "+" : ""}
            {formatPrice(ticker.priceChange)}
          </span>
          <span className={classes.label}>24h</span>
        </div>
      )}

      {/* Volume */}
      {showVolume && (
        <div className={`flex items-center gap-2 ${classes.volume}`}>
          <span className={classes.label}>成交量:</span>
          <span className="text-gray-700">
            {formatVolume(ticker.volume24h)}
          </span>
          <span className={classes.label}>成交额:</span>
          <span className="text-gray-700">
            {formatVolume(ticker.quoteVolume24h)}
          </span>
        </div>
      )}

      {/* High/Low */}
      <div className={`flex items-center gap-3 ${classes.volume}`}>
        <div className="flex items-center gap-1">
          <span className={classes.label}>高:</span>
          <span className="text-green-600">{formatPrice(ticker.high24h)}</span>
        </div>
        <div className="flex items-center gap-1">
          <span className={classes.label}>低:</span>
          <span className="text-red-600">{formatPrice(ticker.low24h)}</span>
        </div>
      </div>

      {/* Connection Status */}
      {!isConnected && (
        <span className="text-xs text-amber-500 mt-1">实时数据连接中...</span>
      )}
    </div>
  );
}
