/**
 * SymbolInfoPanel Component
 * Comprehensive symbol information and details sidebar
 * OQI-003: Trading y Charts
 */

import React, { useState, useMemo } from 'react';
import {
  Info,
  TrendingUp,
  TrendingDown,
  BarChart3,
  Activity,
  Clock,
  DollarSign,
  Percent,
  Globe,
  Star,
  StarOff,
  ExternalLink,
  RefreshCw,
  ChevronDown,
  ChevronUp,
  Zap,
  AlertCircle,
} from 'lucide-react';

export interface SymbolStats {
  price: number;
  change24h: number;
  changePercent24h: number;
  high24h: number;
  low24h: number;
  open24h: number;
  volume24h: number;
  volumeQuote24h: number;
  marketCap?: number;
  circulatingSupply?: number;
  totalSupply?: number;
  allTimeHigh?: number;
  allTimeLow?: number;
  athDate?: string;
  atlDate?: string;
}

export interface SymbolInfo {
  symbol: string;
  name: string;
  baseAsset: string;
  quoteAsset: string;
  exchange: string;
  type: 'spot' | 'futures' | 'forex' | 'crypto';
  status: 'trading' | 'halt' | 'break';
  minNotional?: number;
  tickSize?: number;
  stepSize?: number;
  maxLeverage?: number;
  tradingHours?: string;
  description?: string;
}

interface RelatedSymbol {
  symbol: string;
  correlation: number;
  change24h: number;
}

interface SymbolInfoPanelProps {
  symbol: string;
  info?: SymbolInfo;
  stats?: SymbolStats;
  relatedSymbols?: RelatedSymbol[];
  isFavorite?: boolean;
  onToggleFavorite?: (symbol: string) => void;
  onSymbolSelect?: (symbol: string) => void;
  onRefresh?: () => void;
  isLoading?: boolean;
  compact?: boolean;
}

const SymbolInfoPanel: React.FC<SymbolInfoPanelProps> = ({
  symbol,
  info,
  stats,
  relatedSymbols = [],
  isFavorite = false,
  onToggleFavorite,
  onSymbolSelect,
  onRefresh,
  isLoading = false,
  compact = false,
}) => {
  const [expandedSection, setExpandedSection] = useState<string | null>('stats');

  const priceChangeColor = useMemo(() => {
    if (!stats) return 'text-gray-400';
    return stats.change24h >= 0 ? 'text-green-400' : 'text-red-400';
  }, [stats]);

  const formatNumber = (num: number, decimals = 2) => {
    if (num >= 1e9) return `${(num / 1e9).toFixed(decimals)}B`;
    if (num >= 1e6) return `${(num / 1e6).toFixed(decimals)}M`;
    if (num >= 1e3) return `${(num / 1e3).toFixed(decimals)}K`;
    return num.toFixed(decimals);
  };

  const formatPrice = (price: number) => {
    if (price >= 1000) return price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    if (price >= 1) return price.toFixed(4);
    return price.toFixed(8);
  };

  const formatPercent = (percent: number) => {
    const sign = percent >= 0 ? '+' : '';
    return `${sign}${percent.toFixed(2)}%`;
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'trading':
        return <span className="px-2 py-0.5 bg-green-500/20 text-green-400 rounded text-xs">Trading</span>;
      case 'halt':
        return <span className="px-2 py-0.5 bg-red-500/20 text-red-400 rounded text-xs">Halted</span>;
      case 'break':
        return <span className="px-2 py-0.5 bg-yellow-500/20 text-yellow-400 rounded text-xs">Break</span>;
      default:
        return null;
    }
  };

  const toggleSection = (section: string) => {
    setExpandedSection(expandedSection === section ? null : section);
  };

  return (
    <div className={`bg-gray-800/50 rounded-xl border border-gray-700 ${compact ? 'p-3' : 'p-4'}`}>
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-blue-500/20 rounded-lg">
            <Info className="w-5 h-5 text-blue-400" />
          </div>
          <div>
            <div className="flex items-center gap-2">
              <h3 className="font-bold text-white text-lg">{symbol}</h3>
              {info && getStatusBadge(info.status)}
            </div>
            {info && (
              <p className="text-xs text-gray-500">{info.name}</p>
            )}
          </div>
        </div>

        <div className="flex items-center gap-2">
          <button
            onClick={() => onToggleFavorite?.(symbol)}
            className={`p-2 rounded-lg transition-colors ${
              isFavorite
                ? 'text-yellow-400 bg-yellow-500/10'
                : 'text-gray-500 hover:text-yellow-400 hover:bg-gray-700'
            }`}
          >
            {isFavorite ? <Star className="w-4 h-4 fill-current" /> : <StarOff className="w-4 h-4" />}
          </button>
          <button
            onClick={onRefresh}
            disabled={isLoading}
            className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors disabled:opacity-50"
          >
            <RefreshCw className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`} />
          </button>
        </div>
      </div>

      {/* Price Display */}
      {stats && (
        <div className="p-4 bg-gray-900/50 rounded-lg mb-4">
          <div className="flex items-end justify-between mb-2">
            <div>
              <span className="text-3xl font-bold text-white">${formatPrice(stats.price)}</span>
              <div className="flex items-center gap-2 mt-1">
                {stats.change24h >= 0 ? (
                  <TrendingUp className="w-4 h-4 text-green-400" />
                ) : (
                  <TrendingDown className="w-4 h-4 text-red-400" />
                )}
                <span className={`font-medium ${priceChangeColor}`}>
                  {stats.change24h >= 0 ? '+' : ''}{formatPrice(stats.change24h)}
                </span>
                <span className={`text-sm ${priceChangeColor}`}>
                  ({formatPercent(stats.changePercent24h)})
                </span>
              </div>
            </div>
            <div className="text-right text-xs text-gray-500">
              <div>24h High: <span className="text-green-400">${formatPrice(stats.high24h)}</span></div>
              <div>24h Low: <span className="text-red-400">${formatPrice(stats.low24h)}</span></div>
            </div>
          </div>

          {/* Mini Stats Row */}
          <div className="grid grid-cols-3 gap-3 pt-3 border-t border-gray-700">
            <div className="text-center">
              <div className="text-xs text-gray-500">Volume</div>
              <div className="text-white font-medium">${formatNumber(stats.volumeQuote24h)}</div>
            </div>
            {stats.marketCap && (
              <div className="text-center">
                <div className="text-xs text-gray-500">Market Cap</div>
                <div className="text-white font-medium">${formatNumber(stats.marketCap)}</div>
              </div>
            )}
            <div className="text-center">
              <div className="text-xs text-gray-500">Open</div>
              <div className="text-white font-medium">${formatPrice(stats.open24h)}</div>
            </div>
          </div>
        </div>
      )}

      {/* Expandable Sections */}
      <div className="space-y-2">
        {/* Stats Section */}
        {stats && (
          <div className="bg-gray-900/50 rounded-lg">
            <button
              onClick={() => toggleSection('stats')}
              className="w-full flex items-center justify-between p-3 hover:bg-gray-800/50 transition-colors"
            >
              <div className="flex items-center gap-2">
                <BarChart3 className="w-4 h-4 text-gray-400" />
                <span className="text-sm font-medium text-white">Statistics</span>
              </div>
              {expandedSection === 'stats' ? (
                <ChevronUp className="w-4 h-4 text-gray-500" />
              ) : (
                <ChevronDown className="w-4 h-4 text-gray-500" />
              )}
            </button>

            {expandedSection === 'stats' && (
              <div className="px-3 pb-3 space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">24h Volume ({info?.baseAsset})</span>
                  <span className="text-white">{formatNumber(stats.volume24h)}</span>
                </div>
                {stats.allTimeHigh && (
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-500">All-Time High</span>
                    <div className="text-right">
                      <span className="text-green-400">${formatPrice(stats.allTimeHigh)}</span>
                      {stats.athDate && (
                        <div className="text-xs text-gray-600">{stats.athDate}</div>
                      )}
                    </div>
                  </div>
                )}
                {stats.allTimeLow && (
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-500">All-Time Low</span>
                    <div className="text-right">
                      <span className="text-red-400">${formatPrice(stats.allTimeLow)}</span>
                      {stats.atlDate && (
                        <div className="text-xs text-gray-600">{stats.atlDate}</div>
                      )}
                    </div>
                  </div>
                )}
                {stats.circulatingSupply && (
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-500">Circulating Supply</span>
                    <span className="text-white">{formatNumber(stats.circulatingSupply, 0)}</span>
                  </div>
                )}
              </div>
            )}
          </div>
        )}

        {/* Info Section */}
        {info && (
          <div className="bg-gray-900/50 rounded-lg">
            <button
              onClick={() => toggleSection('info')}
              className="w-full flex items-center justify-between p-3 hover:bg-gray-800/50 transition-colors"
            >
              <div className="flex items-center gap-2">
                <Activity className="w-4 h-4 text-gray-400" />
                <span className="text-sm font-medium text-white">Trading Info</span>
              </div>
              {expandedSection === 'info' ? (
                <ChevronUp className="w-4 h-4 text-gray-500" />
              ) : (
                <ChevronDown className="w-4 h-4 text-gray-500" />
              )}
            </button>

            {expandedSection === 'info' && (
              <div className="px-3 pb-3 space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">Exchange</span>
                  <span className="text-white">{info.exchange}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">Type</span>
                  <span className="text-white capitalize">{info.type}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">Base Asset</span>
                  <span className="text-white">{info.baseAsset}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">Quote Asset</span>
                  <span className="text-white">{info.quoteAsset}</span>
                </div>
                {info.tickSize && (
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-500">Tick Size</span>
                    <span className="text-white">{info.tickSize}</span>
                  </div>
                )}
                {info.minNotional && (
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-500">Min Order</span>
                    <span className="text-white">${info.minNotional}</span>
                  </div>
                )}
                {info.maxLeverage && (
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-500">Max Leverage</span>
                    <span className="text-yellow-400">{info.maxLeverage}x</span>
                  </div>
                )}
                {info.tradingHours && (
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-500">Trading Hours</span>
                    <span className="text-white">{info.tradingHours}</span>
                  </div>
                )}
              </div>
            )}
          </div>
        )}

        {/* Related Symbols */}
        {relatedSymbols.length > 0 && (
          <div className="bg-gray-900/50 rounded-lg">
            <button
              onClick={() => toggleSection('related')}
              className="w-full flex items-center justify-between p-3 hover:bg-gray-800/50 transition-colors"
            >
              <div className="flex items-center gap-2">
                <Globe className="w-4 h-4 text-gray-400" />
                <span className="text-sm font-medium text-white">Related Symbols</span>
              </div>
              {expandedSection === 'related' ? (
                <ChevronUp className="w-4 h-4 text-gray-500" />
              ) : (
                <ChevronDown className="w-4 h-4 text-gray-500" />
              )}
            </button>

            {expandedSection === 'related' && (
              <div className="px-3 pb-3 space-y-1">
                {relatedSymbols.map((related) => (
                  <button
                    key={related.symbol}
                    onClick={() => onSymbolSelect?.(related.symbol)}
                    className="w-full flex items-center justify-between p-2 hover:bg-gray-800 rounded transition-colors"
                  >
                    <div className="flex items-center gap-2">
                      <span className="text-white text-sm">{related.symbol}</span>
                      <span className="text-xs text-gray-500">
                        {related.correlation > 0 ? '+' : ''}{(related.correlation * 100).toFixed(0)}% corr
                      </span>
                    </div>
                    <span className={`text-sm ${related.change24h >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                      {formatPercent(related.change24h)}
                    </span>
                  </button>
                ))}
              </div>
            )}
          </div>
        )}

        {/* Description */}
        {info?.description && (
          <div className="bg-gray-900/50 rounded-lg">
            <button
              onClick={() => toggleSection('desc')}
              className="w-full flex items-center justify-between p-3 hover:bg-gray-800/50 transition-colors"
            >
              <div className="flex items-center gap-2">
                <AlertCircle className="w-4 h-4 text-gray-400" />
                <span className="text-sm font-medium text-white">About</span>
              </div>
              {expandedSection === 'desc' ? (
                <ChevronUp className="w-4 h-4 text-gray-500" />
              ) : (
                <ChevronDown className="w-4 h-4 text-gray-500" />
              )}
            </button>

            {expandedSection === 'desc' && (
              <div className="px-3 pb-3">
                <p className="text-sm text-gray-400 leading-relaxed">{info.description}</p>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Quick Actions */}
      {!compact && (
        <div className="mt-4 pt-4 border-t border-gray-700">
          <div className="grid grid-cols-2 gap-2">
            <button className="flex items-center justify-center gap-2 py-2 bg-green-600 hover:bg-green-500 text-white rounded-lg text-sm font-medium transition-colors">
              <TrendingUp className="w-4 h-4" />
              Buy
            </button>
            <button className="flex items-center justify-center gap-2 py-2 bg-red-600 hover:bg-red-500 text-white rounded-lg text-sm font-medium transition-colors">
              <TrendingDown className="w-4 h-4" />
              Sell
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default SymbolInfoPanel;
