import { useState, memo } from 'react';
import { BacktestChart } from './BacktestChart';
import { ErrorBoundary } from '../../../components/ErrorBoundary';
import { CompactPerformanceMetrics } from './CompactPerformanceMetrics';
import { PositionsSummary } from './PositionsSummary';

interface BacktestPlaybackProps {
  result: any | null;
  isLoading: boolean;
}

export const BacktestPlayback = memo(function BacktestPlayback({ result, isLoading }: BacktestPlaybackProps) {
  const [showPositions, setShowPositions] = useState(false);

  if (isLoading) {
    return (
      <div className="h-full flex items-center justify-center">
        <div className="text-text-secondary">Loading playback data...</div>
      </div>
    );
  }

  if (!result) {
    return (
      <div className="h-full flex items-center justify-center">
        <div className="text-text-secondary">No data available</div>
      </div>
    );
  }

  // Get positions from the result
  let openPositions: any[] = [];
  let closedPositions: any[] = [];
  
  if (result.positions) {
    if (Array.isArray(result.positions)) {
      result.positions.forEach((p: any) => {
        if (p.quantity !== 0) {
          openPositions.push(p);
        } else if (p.realizedPnl !== 0) {
          closedPositions.push(p);
        }
      });
    } else if (typeof result.positions === 'object') {
      // Convert positions object to array
      Object.entries(result.positions).forEach(([symbol, position]: [string, any]) => {
        const pos = { symbol, ...position };
        if (position.quantity !== 0) {
          openPositions.push(pos);
        } else if (position.realizedPnl !== 0) {
          closedPositions.push(pos);
        }
      });
    }
  }

  return (
    <div className="h-full flex flex-col gap-4">
      {/* Chart Section */}
      <div className="flex-1 min-h-0">
        <ErrorBoundary
          fallback={
            <div className="h-full flex items-center justify-center bg-surface-secondary rounded-lg border border-border">
              <div className="text-center p-4">
                <p className="text-text-secondary mb-4">Chart failed to load</p>
                <button
                  onClick={() => window.location.reload()}
                  className="text-primary-500 hover:text-primary-600 font-medium"
                >
                  Reload Page
                </button>
              </div>
            </div>
          }
        >
          <BacktestChart 
            result={result} 
            isLoading={isLoading} 
          />
        </ErrorBoundary>
      </div>

      {/* Performance Metrics and Positions - Fixed height section */}
      <div className="flex-shrink-0 grid grid-cols-1 lg:grid-cols-2 gap-4">
        <CompactPerformanceMetrics result={result} isLoading={isLoading} />
        <PositionsSummary 
          openPositions={openPositions}
          closedPositions={closedPositions}
          onExpand={() => setShowPositions(true)}
        />
      </div>
      
      {/* Detailed Positions View - Optional expanded view */}
      {showPositions && (openPositions.length > 0 || closedPositions.length > 0) && (
        <div className="flex-shrink-0">
          <div className="bg-surface-secondary rounded-lg border border-border p-4">
            <div className="flex justify-between items-center mb-3">
              <h3 className="text-sm font-medium text-text-primary">
                All Positions
              </h3>
              <button
                onClick={() => setShowPositions(!showPositions)}
                className="text-xs text-text-secondary hover:text-text-primary"
              >
                Close
              </button>
            </div>
            
            <div className="space-y-4">
              {openPositions.length > 0 && (
                <div>
                  <h4 className="text-sm font-medium text-text-secondary mb-2">Open Positions ({openPositions.length})</h4>
                  <div className="space-y-2">
                <div className="grid grid-cols-6 gap-2 text-xs font-medium text-text-secondary pb-2 border-b border-border">
                  <div>Symbol</div>
                  <div>Side</div>
                  <div className="text-right">Quantity</div>
                  <div className="text-right">Entry Price</div>
                  <div className="text-right">Current Price</div>
                  <div className="text-right">P&L</div>
                </div>
                
                {openPositions.map((position, index) => {
                  const quantity = position.quantity || 0;
                  const avgPrice = position.averagePrice || position.avgPrice || 0;
                  const currentPrice = position.currentPrice || position.lastPrice || avgPrice;
                  const side = quantity > 0 ? 'long' : 'short';
                  const absQuantity = Math.abs(quantity);
                  const pnl = (currentPrice - avgPrice) * quantity;
                  const pnlPercent = avgPrice > 0 ? (pnl / (avgPrice * absQuantity)) * 100 : 0;
                  
                  return (
                    <div key={index} className="grid grid-cols-6 gap-2 text-sm">
                      <div className="font-medium text-text-primary">{position.symbol}</div>
                      <div className={side === 'long' ? 'text-success' : 'text-error'}>
                        {side.toUpperCase()}
                      </div>
                      <div className="text-right text-text-primary">{absQuantity}</div>
                      <div className="text-right text-text-primary">
                        ${avgPrice.toFixed(2)}
                      </div>
                      <div className="text-right text-text-primary">
                        ${currentPrice.toFixed(2)}
                      </div>
                      <div className={`text-right font-medium ${pnl >= 0 ? 'text-success' : 'text-error'}`}>
                        ${pnl.toFixed(2)} ({pnlPercent >= 0 ? '+' : ''}{pnlPercent.toFixed(2)}%)
                      </div>
                    </div>
                  );
                })}
                  </div>
                </div>
              )}
              
              {closedPositions.length > 0 && (
                <div>
                  <h4 className="text-sm font-medium text-text-secondary mb-2">Closed Positions ({closedPositions.length})</h4>
                  <div className="space-y-1">
                    {closedPositions.map((position, index) => (
                      <div key={index} className="flex items-center justify-between py-2 px-3 bg-surface rounded">
                        <div className="flex items-center space-x-3">
                          <span className="font-medium text-text-primary">{position.symbol}</span>
                          <span className="text-sm text-text-secondary">Closed</span>
                        </div>
                        <div className="text-right">
                          <div className={`text-sm font-medium ${position.realizedPnl >= 0 ? 'text-success' : 'text-error'}`}>
                            Realized P&L: ${position.realizedPnl.toFixed(2)}
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
                
              <div className="pt-3 mt-3 border-t border-border grid grid-cols-3 gap-4 text-sm">
                <div className="text-center">
                  <div className="text-text-secondary text-xs">Unrealized P&L</div>
                  <div className={`font-medium ${
                    openPositions.reduce((sum, p) => {
                      const quantity = p.quantity || 0;
                      const avgPrice = p.averagePrice || p.avgPrice || 0;
                      const currentPrice = p.currentPrice || p.lastPrice || avgPrice;
                      return sum + ((currentPrice - avgPrice) * quantity);
                    }, 0) >= 0 ? 'text-success' : 'text-error'
                  }`}>
                    ${openPositions.reduce((sum, p) => {
                      const quantity = p.quantity || 0;
                      const avgPrice = p.averagePrice || p.avgPrice || 0;
                      const currentPrice = p.currentPrice || p.lastPrice || avgPrice;
                      return sum + ((currentPrice - avgPrice) * quantity);
                    }, 0).toFixed(2)}
                  </div>
                </div>
                <div className="text-center">
                  <div className="text-text-secondary text-xs">Realized P&L</div>
                  <div className={`font-medium ${
                    closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0) >= 0 ? 'text-success' : 'text-error'
                  }`}>
                    ${closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0).toFixed(2)}
                  </div>
                </div>
                <div className="text-center">
                  <div className="text-text-secondary text-xs">Total P&L</div>
                  <div className={`font-medium ${
                    (openPositions.reduce((sum, p) => {
                      const quantity = p.quantity || 0;
                      const avgPrice = p.averagePrice || p.avgPrice || 0;
                      const currentPrice = p.currentPrice || p.lastPrice || avgPrice;
                      return sum + ((currentPrice - avgPrice) * quantity);
                    }, 0) + closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0)) >= 0 ? 'text-success' : 'text-error'
                  }`}>
                    ${(openPositions.reduce((sum, p) => {
                      const quantity = p.quantity || 0;
                      const avgPrice = p.averagePrice || p.avgPrice || 0;
                      const currentPrice = p.currentPrice || p.lastPrice || avgPrice;
                      return sum + ((currentPrice - avgPrice) * quantity);
                    }, 0) + closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0)).toFixed(2)}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
});