import { useMemo } from 'react';
import type { Trade as PortfolioTrade } from '@/types';
import type { Trade as AdvancedMetricsTrade } from '@/components/AdvancedMetricsDashboard';

export type TradeDatasetSource = 'live' | 'sample';

const TIMEFRAMES = ['1m', '3m', '5m', '15m', '1h', '4h', 'Daily'];
const SIGNAL_TYPES: AdvancedMetricsTrade['signalType'][] = [
  'RSI_CROSSOVER',
  'MA_CROSSOVER',
  'BB_BREAKOUT',
  'MACD',
  'SUPPORT_BOUNCE',
  'TREND_CONFIRMATION',
  'NEWS_TRIGGERED',
];

const now = Date.now();
const sampleTimestamp = (minutesAgo: number) => new Date(now - minutesAgo * 60 * 1000).toISOString();

const SAMPLE_TRADES: AdvancedMetricsTrade[] = [
  {
    id: 'sample-1',
    timeframe: '1m',
    signalType: 'RSI_CROSSOVER',
    entry: 2031.5,
    exit: 2033.6,
    quantity: 3,
    profitable: true,
    pnl: 160.5,
    grossPnL: 162.9,
    slippage: 2.4,
    volatility: 0.8,
    volume: 6100.8,
    confidence: 62,
    timestamp: sampleTimestamp(45),
  },
  {
    id: 'sample-2',
    timeframe: '5m',
    signalType: 'MA_CROSSOVER',
    entry: 2030.2,
    exit: 2034.1,
    quantity: 2,
    profitable: true,
    pnl: 285.8,
    grossPnL: 287.6,
    slippage: 1.8,
    volatility: 1.05,
    volume: 4068.2,
    confidence: 68,
    timestamp: sampleTimestamp(90),
  },
  {
    id: 'sample-3',
    timeframe: '15m',
    signalType: 'TREND_CONFIRMATION',
    entry: 2028.4,
    exit: 2035.0,
    quantity: 1.8,
    profitable: true,
    pnl: 420.2,
    grossPnL: 421.5,
    slippage: 1.3,
    volatility: 1.4,
    volume: 3663,
    confidence: 78,
    timestamp: sampleTimestamp(150),
  },
  {
    id: 'sample-4',
    timeframe: '1h',
    signalType: 'MACD',
    entry: 2036.1,
    exit: 2033.0,
    quantity: 1.5,
    profitable: false,
    pnl: -95.3,
    grossPnL: -93.1,
    slippage: 2.2,
    volatility: 1.9,
    volume: 3049.5,
    confidence: 54,
    timestamp: sampleTimestamp(210),
  },
  {
    id: 'sample-5',
    timeframe: '4h',
    signalType: 'SUPPORT_BOUNCE',
    entry: 2026.0,
    exit: 2033.8,
    quantity: 2.1,
    profitable: true,
    pnl: 310.6,
    grossPnL: 312.2,
    slippage: 1.6,
    volatility: 2.2,
    volume: 4270.98,
    confidence: 73,
    timestamp: sampleTimestamp(300),
  },
  {
    id: 'sample-6',
    timeframe: 'Daily',
    signalType: 'NEWS_TRIGGERED',
    entry: 2038.4,
    exit: 2034.5,
    quantity: 1.2,
    profitable: false,
    pnl: -140.6,
    grossPnL: -137.5,
    slippage: 3.1,
    volatility: 2.8,
    volume: 2441.4,
    confidence: 48,
    timestamp: sampleTimestamp(420),
  },
  {
    id: 'sample-7',
    timeframe: '15m',
    signalType: 'BB_BREAKOUT',
    entry: 2031.8,
    exit: 2034.0,
    quantity: 2.6,
    profitable: true,
    pnl: 85.3,
    grossPnL: 86.1,
    slippage: 0.8,
    volatility: 0.95,
    volume: 5288.4,
    confidence: 57,
    timestamp: sampleTimestamp(510),
  },
  {
    id: 'sample-8',
    timeframe: '5m',
    signalType: 'TREND_CONFIRMATION',
    entry: 2029.7,
    exit: 2034.8,
    quantity: 2.4,
    profitable: true,
    pnl: 210.5,
    grossPnL: 211.7,
    slippage: 1.2,
    volatility: 1.3,
    volume: 4883.52,
    confidence: 81,
    timestamp: sampleTimestamp(600),
  },
];

const toAdvancedTrade = (trade: PortfolioTrade, index: number): AdvancedMetricsTrade => {
  const seed = trade.timestamp ?? index;
  const timeframe = TIMEFRAMES[Math.abs(seed + index) % TIMEFRAMES.length];
  const signalType = SIGNAL_TYPES[Math.abs(seed * 3 + index) % SIGNAL_TYPES.length];
  const quantity = Math.max(trade.quantity, 0.0001);
  const pnl = trade.pnl ?? 0;
  const exit = trade.price;
  const entry = exit - pnl / quantity;
  const volatility = Number((0.45 + ((seed % 12) * 0.2)).toFixed(2));
  const slippage = Number((Math.abs(exit) * 0.0001 * (1 + (seed % 5) * 0.15) + 0.08).toFixed(2));
  const grossPnL = Number((pnl + slippage).toFixed(2));
  const confidenceBase = pnl >= 0 ? 65 : 55;
  const confidence = Math.max(45, Math.min(95, confidenceBase + ((seed % 7) - 3) * 4));
  const volume = Number((quantity * exit).toFixed(2));

  return {
    id: trade.id,
    timeframe,
    signalType,
    entry: Number(entry.toFixed(2)) || Number(exit.toFixed(2)),
    exit: Number(exit.toFixed(2)),
    quantity: Number(quantity.toFixed(4)),
    profitable: pnl >= 0,
    pnl: Number(pnl.toFixed(2)),
    grossPnL,
    slippage,
    volatility,
    volume,
    confidence,
    timestamp: new Date(trade.timestamp ?? Date.now()).toISOString(),
  };
};

export const useAdvancedTradeMetrics = (trades?: PortfolioTrade[] | null) => {
  return useMemo<{ trades: AdvancedMetricsTrade[]; source: TradeDatasetSource }>(() => {
    if (!trades || trades.length === 0) {
      return { trades: SAMPLE_TRADES, source: 'sample' };
    }

    const executed = trades.filter((trade) => trade.action === 'SELL' && typeof trade.pnl === 'number');
    if (executed.length === 0) {
      return { trades: SAMPLE_TRADES, source: 'sample' };
    }

    return {
      trades: executed.map(toAdvancedTrade),
      source: 'live',
    };
  }, [trades]);
};
