import { useMemo, useState } from 'react';
import { Calendar, TrendingUp, TrendingDown, Target } from 'lucide-react';

/**
 * Multi-day position tracking for swing trades
 * Tracks entries, profit tiers, duration, and multi-day targets
 */

export interface SwingPosition {
  id: string;
  entryDate: string;
  entryPrice: number;
  quantity: number;
  currentPrice?: number;
  direction: 'LONG' | 'SHORT';
  
  // Profit targets
  target1Price?: number;
  target1Closed?: boolean;
  target2Price?: number;
  target2Closed?: boolean;
  target3Price?: number;
  target3Closed?: boolean;
  
  // Stop loss
  stopLoss?: number;
  
  // Notes
  notes?: string;
}

export interface PositionMetrics {
  totalPositions: number;
  activePositions: number;
  completedPositions: number;
  avgHoldDays: number;
  winRate: number; // %
  totalProfit: number;
  avgProfitPerTrade: number;
}

export interface MultiDayTrackerProps {
  positions: SwingPosition[];
  onPositionUpdate?: (position: SwingPosition) => void;
  onMetricsUpdate?: (metrics: PositionMetrics) => void;
}

export default function MultiDayPositionTracker({
  positions,
  onMetricsUpdate,
}: MultiDayTrackerProps) {
  const [expandedId, setExpandedId] = useState<string | null>(null);

  // Calculate position metrics
  const metrics = useMemo(() => {
    if (positions.length === 0) {
      return {
        totalPositions: 0,
        activePositions: 0,
        completedPositions: 0,
        avgHoldDays: 0,
        winRate: 0,
        totalProfit: 0,
        avgProfitPerTrade: 0,
      };
    }

    const active = positions.filter(p => !p.target3Closed).length;
    const completed = positions.length - active;

    // Calculate hold days
    const holdDays = positions
      .map(p => {
        const entry = new Date(p.entryDate);
        const now = new Date();
        return (now.getTime() - entry.getTime()) / (1000 * 60 * 60 * 24);
      })
      .reduce((a, b) => a + b, 0) / positions.length;

    // Calculate profits
    let totalProfit = 0;
    let winningTrades = 0;

    positions.forEach(p => {
      const exitPrice = p.target3Closed && p.target3Price ? p.target3Price : p.currentPrice || p.entryPrice;
      const tradeProfit = 
        p.direction === 'LONG'
          ? (exitPrice - p.entryPrice) * p.quantity
          : (p.entryPrice - exitPrice) * p.quantity;
      
      totalProfit += tradeProfit;
      if (tradeProfit > 0) winningTrades += 1;
    });

    const metrics: PositionMetrics = {
      totalPositions: positions.length,
      activePositions: active,
      completedPositions: completed,
      avgHoldDays: holdDays,
      winRate: (winningTrades / positions.length) * 100,
      totalProfit,
      avgProfitPerTrade: totalProfit / positions.length,
    };

    onMetricsUpdate?.(metrics);
    return metrics;
  }, [positions, onMetricsUpdate]);

  // Calculate individual position metrics
  const getPositionMetrics = (position: SwingPosition) => {
    const entryDate = new Date(position.entryDate);
    const now = new Date();
    const holdDays = (now.getTime() - entryDate.getTime()) / (1000 * 60 * 60 * 24);

    const exitPrice = position.currentPrice || position.entryPrice;
    const profit = position.direction === 'LONG'
      ? (exitPrice - position.entryPrice) * position.quantity
      : (position.entryPrice - exitPrice) * position.quantity;

    const profitPercent = position.direction === 'LONG'
      ? ((exitPrice - position.entryPrice) / position.entryPrice) * 100
      : ((position.entryPrice - exitPrice) / position.entryPrice) * 100;

    return { holdDays: Math.round(holdDays * 10) / 10, profit, profitPercent };
  };

  // Format date to readable format
  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: '2-digit' });
  };

  if (positions.length === 0) {
    return (
      <div className="rounded-lg border border-slate-700 bg-slate-900 p-6 text-center">
        <Calendar className="w-8 h-8 text-slate-600 mx-auto mb-2" />
        <p className="text-slate-400">No active swing positions</p>
        <p className="text-xs text-slate-600 mt-1">Multi-day positions will appear here</p>
      </div>
    );
  }

  return (
    <div className="rounded-lg border border-slate-700 bg-slate-900 space-y-4 overflow-hidden">
      {/* Header Summary */}
      <div className="bg-slate-800/50 p-4 border-b border-slate-700">
        <h3 className="font-semibold text-slate-200 mb-3">Multi-Day Position Tracker</h3>
        
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
          <div className="bg-slate-800/50 rounded px-3 py-2">
            <p className="text-xs text-slate-500">Total Positions</p>
            <p className="text-lg font-bold text-slate-300">{metrics.totalPositions}</p>
            <p className="text-xs text-slate-600">
              {metrics.activePositions} active
            </p>
          </div>
          
          <div className="bg-slate-800/50 rounded px-3 py-2">
            <p className="text-xs text-slate-500">Avg Hold Time</p>
            <p className="text-lg font-bold text-slate-300">{metrics.avgHoldDays.toFixed(1)}d</p>
            <p className="text-xs text-slate-600">
              {metrics.avgHoldDays > 3 ? 'Strong swing' : metrics.avgHoldDays > 1 ? 'Good swing' : 'Quick swing'}
            </p>
          </div>
          
          <div className="bg-slate-800/50 rounded px-3 py-2">
            <p className="text-xs text-slate-500">Win Rate</p>
            <p className={`text-lg font-bold ${metrics.winRate >= 60 ? 'text-emerald-400' : metrics.winRate >= 40 ? 'text-amber-400' : 'text-red-400'}`}>
              {metrics.winRate.toFixed(1)}%
            </p>
            <p className="text-xs text-slate-600">
              {metrics.completedPositions} closed
            </p>
          </div>
          
          <div className="bg-slate-800/50 rounded px-3 py-2">
            <p className="text-xs text-slate-500">Total P&L</p>
            <p className={`text-lg font-bold ${metrics.totalProfit >= 0 ? 'text-emerald-400' : 'text-red-400'}`}>
              ${Math.abs(metrics.totalProfit).toFixed(2)}
            </p>
            <p className="text-xs text-slate-600">
              ${(metrics.avgProfitPerTrade).toFixed(2)}/trade
            </p>
          </div>
        </div>
      </div>

      {/* Positions List */}
      <div className="px-4 pb-4 space-y-3">
        {positions.map((position) => {
          const { holdDays, profit, profitPercent } = getPositionMetrics(position);
          const isExpanded = expandedId === position.id;
          const isLong = position.direction === 'LONG';
          const currentPrice_ = position.currentPrice || position.entryPrice;

          // Determine status
          let status: 'active' | 'partial' | 'completed' = 'active';
          let closedCount = 0;
          if (position.target1Closed) closedCount++;
          if (position.target2Closed) closedCount++;
          if (position.target3Closed) closedCount++;
          
          if (closedCount === 3) status = 'completed';
          else if (closedCount > 0) status = 'partial';

          return (
            <div
              key={position.id}
              className={`rounded-lg border transition-all cursor-pointer ${
                isExpanded
                  ? 'border-blue-500/40 bg-blue-500/5'
                  : status === 'completed'
                  ? 'border-slate-700 bg-slate-800/30'
                  : 'border-slate-700 bg-slate-800/50 hover:bg-slate-800/70'
              }`}
              onClick={() => setExpandedId(isExpanded ? null : position.id)}
            >
              {/* Main Row */}
              <div className="p-3 flex items-center justify-between gap-2">
                {/* Left: Entry & Direction */}
                <div className="flex items-center gap-3 min-w-0">
                  <div className={`p-2 rounded-lg ${isLong ? 'bg-emerald-500/20' : 'bg-red-500/20'}`}>
                    {isLong ? (
                      <TrendingUp className="w-4 h-4 text-emerald-400" />
                    ) : (
                      <TrendingDown className="w-4 h-4 text-red-400" />
                    )}
                  </div>
                  
                  <div className="min-w-0">
                    <p className="text-sm font-mono font-semibold text-slate-200">
                      {position.quantity} oz @ ${position.entryPrice.toFixed(2)}
                    </p>
                    <p className="text-xs text-slate-500">
                      {formatDate(position.entryDate)} • {holdDays}d
                    </p>
                  </div>
                </div>

                {/* Right: Current P&L */}
                <div className="text-right">
                  <p className={`text-sm font-bold font-mono ${profit >= 0 ? 'text-emerald-400' : 'text-red-400'}`}>
                    {profit >= 0 ? '+' : ''}{profit.toFixed(2)}
                  </p>
                  <p className={`text-xs font-mono ${profitPercent >= 0 ? 'text-emerald-300' : 'text-red-300'}`}>
                    {profitPercent >= 0 ? '+' : ''}{profitPercent.toFixed(2)}%
                  </p>
                </div>
              </div>

              {/* Expanded Details */}
              {isExpanded && (
                <>
                  <div className="border-t border-slate-700/50 p-3 space-y-3">
                    {/* Current Price & Movement */}
                    <div className="grid grid-cols-2 gap-2 text-xs">
                      <div className="bg-slate-700/30 rounded px-2 py-1.5">
                        <p className="text-slate-500 mb-0.5">Current Price</p>
                        <p className="font-mono font-semibold text-slate-200">
                          ${currentPrice_.toFixed(2)}
                        </p>
                        <p className={`font-mono text-xs ${
                          (isLong && currentPrice_ > position.entryPrice) || (!isLong && currentPrice_ < position.entryPrice)
                            ? 'text-emerald-400'
                            : 'text-red-400'
                        }`}>
                          {isLong ? currentPrice_ - position.entryPrice >= 0 ? '+' : '' : currentPrice_ - position.entryPrice <= 0 ? '+' : ''}
                          ${(isLong ? currentPrice_ - position.entryPrice : position.entryPrice - currentPrice_).toFixed(2)}
                        </p>
                      </div>

                      <div className="bg-slate-700/30 rounded px-2 py-1.5">
                        <p className="text-slate-500 mb-0.5">Stop Loss</p>
                        <p className="font-mono font-semibold text-slate-200">
                          ${(position.stopLoss || position.entryPrice * 0.98).toFixed(2)}
                        </p>
                        <p className={`font-mono text-xs ${
                          (isLong && currentPrice_ > (position.stopLoss || position.entryPrice * 0.98)) || 
                          (!isLong && currentPrice_ < (position.stopLoss || position.entryPrice * 0.98))
                            ? 'text-emerald-400'
                            : 'text-red-400'
                        }`}>
                          {(isLong ? currentPrice_ - (position.stopLoss || position.entryPrice * 0.98) : 
                            (position.stopLoss || position.entryPrice * 0.98) - currentPrice_).toFixed(2)} buffer
                        </p>
                      </div>
                    </div>

                    {/* Profit Targets */}
                    <div className="space-y-2">
                      <p className="text-xs font-semibold text-slate-400">Profit Targets</p>
                      <div className="space-y-1.5">
                        {[1, 2, 3].map((tier) => {
                          const targetPrice = tier === 1 ? position.target1Price :
                                            tier === 2 ? position.target2Price :
                                            position.target3Price;
                          const isClosed = tier === 1 ? position.target1Closed :
                                         tier === 2 ? position.target2Closed :
                                         position.target3Closed;

                          if (!targetPrice) return null;

                          const targetProfit = isLong
                            ? (targetPrice - position.entryPrice) * (position.quantity / 3)
                            : (position.entryPrice - targetPrice) * (position.quantity / 3);

                          return (
                            <div
                              key={`target-${tier}`}
                              className={`text-xs rounded px-2 py-1.5 flex items-center justify-between ${
                                isClosed
                                  ? 'bg-emerald-500/10 border border-emerald-500/30'
                                  : 'bg-slate-700/30 border border-slate-600/30'
                              }`}
                            >
                              <div className="flex items-center gap-2">
                                <Target className={`w-3 h-3 ${isClosed ? 'text-emerald-400' : 'text-slate-500'}`} />
                                <span className={`font-mono ${isClosed ? 'text-emerald-300 line-through' : 'text-slate-300'}`}>
                                  T{tier}: ${targetPrice.toFixed(2)}
                                </span>
                              </div>
                              <span className={`font-mono ${isClosed ? 'text-emerald-400' : 'text-slate-500'}`}>
                                {isClosed ? '✓ Closed' : `+$${(targetProfit).toFixed(2)}`}
                              </span>
                            </div>
                          );
                        })}
                      </div>
                    </div>

                    {/* Notes */}
                    {position.notes && (
                      <div className="bg-slate-700/20 rounded px-2 py-1.5 text-xs text-slate-300 italic">
                        "{position.notes}"
                      </div>
                    )}

                    {/* Status */}
                    <div className="bg-slate-700/30 rounded px-2 py-1.5 text-xs">
                      <div className="flex items-center justify-between mb-1">
                        <span className="text-slate-500">Position Status</span>
                        <span className={`font-semibold ${
                          status === 'completed' ? 'text-emerald-400' :
                          status === 'partial' ? 'text-amber-400' :
                          'text-blue-400'
                        }`}>
                          {status.charAt(0).toUpperCase() + status.slice(1)}
                        </span>
                      </div>
                      <div className="h-1 bg-slate-600/50 rounded-full overflow-hidden">
                        <div
                          className={`h-full ${
                            status === 'completed' ? 'bg-emerald-500' :
                            status === 'partial' ? 'bg-amber-500' :
                            'bg-blue-500'
                          }`}
                          style={{ width: `${(closedCount / 3) * 100}%` }}
                        />
                      </div>
                    </div>
                  </div>
                </>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}
