/**
 * OrderBookPanel Component
 * Displays market depth with bids and asks
 */

import React, { useEffect, useState, useCallback } from 'react';
import {
  Bars3BottomLeftIcon,
  ArrowPathIcon,
} from '@heroicons/react/24/solid';
import { useTradingStore } from '../../../stores/tradingStore';
import type { OrderBook } from '../../../types/trading.types';

interface OrderBookPanelProps {
  symbol: string;
  onPriceClick?: (price: number) => void;
}

export const OrderBookPanel: React.FC<OrderBookPanelProps> = ({ symbol, onPriceClick }) => {
  const { orderBook, loadingOrderBook, fetchOrderBook } = useTradingStore();
  const [displayRows, setDisplayRows] = useState(10);

  // Fetch order book on mount and symbol change
  useEffect(() => {
    fetchOrderBook(symbol, 20);

    // Refresh every 5 seconds
    const interval = setInterval(() => {
      fetchOrderBook(symbol, 20);
    }, 5000);

    return () => clearInterval(interval);
  }, [symbol, fetchOrderBook]);

  // Calculate max quantity for bar width
  const getMaxQuantity = useCallback((book: OrderBook | null): number => {
    if (!book) return 1;
    const allQuantities = [...book.bids.map((b) => b.quantity), ...book.asks.map((a) => a.quantity)];
    return Math.max(...allQuantities, 1);
  }, []);

  const maxQty = getMaxQuantity(orderBook);

  // Format price
  const formatPrice = (price: number): string => {
    if (price >= 1000) return price.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    if (price >= 1) return price.toFixed(4);
    return price.toFixed(8);
  };

  // Format quantity
  const formatQty = (qty: number): string => {
    if (qty >= 1000000) return `${(qty / 1000000).toFixed(2)}M`;
    if (qty >= 1000) return `${(qty / 1000).toFixed(2)}K`;
    return qty.toFixed(4);
  };

  // Calculate spread
  const getSpread = (): { value: number; percentage: number } | null => {
    if (!orderBook || orderBook.asks.length === 0 || orderBook.bids.length === 0) return null;
    const bestAsk = orderBook.asks[0].price;
    const bestBid = orderBook.bids[0].price;
    const spread = bestAsk - bestBid;
    const percentage = (spread / bestAsk) * 100;
    return { value: spread, percentage };
  };

  const spread = getSpread();

  return (
    <div className="card p-4 space-y-3 h-full flex flex-col">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Bars3BottomLeftIcon className="w-5 h-5 text-purple-400" />
          <h3 className="text-sm font-semibold text-white">Order Book</h3>
        </div>
        <div className="flex items-center gap-2">
          <select
            value={displayRows}
            onChange={(e) => setDisplayRows(Number(e.target.value))}
            className="text-xs bg-gray-700 border border-gray-600 rounded px-1 py-0.5 text-white"
          >
            <option value={5}>5</option>
            <option value={10}>10</option>
            <option value={15}>15</option>
          </select>
          <button
            onClick={() => fetchOrderBook(symbol, 20)}
            disabled={loadingOrderBook}
            className="p-1 text-gray-400 hover:text-white rounded"
          >
            <ArrowPathIcon className={`w-4 h-4 ${loadingOrderBook ? 'animate-spin' : ''}`} />
          </button>
        </div>
      </div>

      {/* Column Headers */}
      <div className="grid grid-cols-3 text-xs text-gray-500 border-b border-gray-700 pb-1">
        <span>Price</span>
        <span className="text-right">Amount</span>
        <span className="text-right">Total</span>
      </div>

      {/* Order Book Content */}
      <div className="flex-1 overflow-hidden flex flex-col">
        {/* Asks (Sell orders) - reversed to show lowest ask at bottom */}
        <div className="flex-1 overflow-y-auto flex flex-col-reverse">
          {orderBook?.asks.slice(0, displayRows).map((entry, idx) => {
            const total = orderBook.asks
              .slice(0, idx + 1)
              .reduce((sum, e) => sum + e.quantity, 0);
            const barWidth = (entry.quantity / maxQty) * 100;

            return (
              <div
                key={`ask-${entry.price}`}
                className="relative grid grid-cols-3 text-xs py-0.5 hover:bg-gray-800 cursor-pointer group"
                onClick={() => onPriceClick?.(entry.price)}
              >
                {/* Background bar */}
                <div
                  className="absolute right-0 top-0 bottom-0 bg-red-500/10 group-hover:bg-red-500/20 transition-colors"
                  style={{ width: `${barWidth}%` }}
                />
                {/* Content */}
                <span className="relative text-red-400 font-mono">{formatPrice(entry.price)}</span>
                <span className="relative text-right text-gray-300 font-mono">{formatQty(entry.quantity)}</span>
                <span className="relative text-right text-gray-500 font-mono">{formatQty(total)}</span>
              </div>
            );
          })}
        </div>

        {/* Spread */}
        {spread && (
          <div className="py-2 border-y border-gray-700 text-center">
            <span className="text-xs text-gray-400">Spread: </span>
            <span className="text-xs text-white font-mono">{formatPrice(spread.value)}</span>
            <span className="text-xs text-gray-500 ml-1">({spread.percentage.toFixed(3)}%)</span>
          </div>
        )}

        {/* Bids (Buy orders) */}
        <div className="flex-1 overflow-y-auto">
          {orderBook?.bids.slice(0, displayRows).map((entry, idx) => {
            const total = orderBook.bids
              .slice(0, idx + 1)
              .reduce((sum, e) => sum + e.quantity, 0);
            const barWidth = (entry.quantity / maxQty) * 100;

            return (
              <div
                key={`bid-${entry.price}`}
                className="relative grid grid-cols-3 text-xs py-0.5 hover:bg-gray-800 cursor-pointer group"
                onClick={() => onPriceClick?.(entry.price)}
              >
                {/* Background bar */}
                <div
                  className="absolute right-0 top-0 bottom-0 bg-green-500/10 group-hover:bg-green-500/20 transition-colors"
                  style={{ width: `${barWidth}%` }}
                />
                {/* Content */}
                <span className="relative text-green-400 font-mono">{formatPrice(entry.price)}</span>
                <span className="relative text-right text-gray-300 font-mono">{formatQty(entry.quantity)}</span>
                <span className="relative text-right text-gray-500 font-mono">{formatQty(total)}</span>
              </div>
            );
          })}
        </div>
      </div>

      {/* Empty State */}
      {!loadingOrderBook && (!orderBook || (orderBook.asks.length === 0 && orderBook.bids.length === 0)) && (
        <div className="text-center py-4 text-gray-500 text-sm">
          No order book data available
        </div>
      )}
    </div>
  );
};

export default OrderBookPanel;
