import type { Trade, Portfolio } from '@/types';

// Export trades to CSV
export const exportTradesToCSV = (trades: Trade[], portfolio: Portfolio): void => {
  const headers = [
    'ID',
    'Timestamp',
    'Action',
    'Quantity',
    'Price',
    'Total',
    'P&L',
    'Date/Time',
  ];

  const rows = trades.map((trade) => [
    trade.id,
    trade.timestamp,
    trade.action,
    trade.quantity.toFixed(4),
    trade.price.toFixed(2),
    trade.total.toFixed(2),
    trade.pnl?.toFixed(2) || 'N/A',
    new Date(trade.timestamp).toLocaleString(),
  ]);

  // Add summary row
  rows.push([]);
  rows.push(['Summary', '', '', '', '', '', '']);
  rows.push(['Total Trades', trades.length.toString(), '', '', '', '', '']);
  rows.push(['Initial Capital', portfolio.initialCapital.toFixed(2), '', '', '', '', '']);
  rows.push(['Current Value', portfolio.totalValue.toFixed(2), '', '', '', '', '']);
  rows.push(['Total P&L', portfolio.totalPnl.toFixed(2), '', '', '', '', '']);
  rows.push([
    'Total P&L %',
    portfolio.totalPnlPercent.toFixed(2) + '%',
    '',
    '',
    '',
    '',
    '',
  ]);

  const csvContent = [headers, ...rows].map((row) => row.join(',')).join('\n');

  downloadFile(csvContent, 'gold_trades_export.csv', 'text/csv');
};

// Export portfolio summary
export const exportPortfolioSummary = (portfolio: Portfolio): void => {
  const summary = {
    exportDate: new Date().toISOString(),
    initialCapital: portfolio.initialCapital,
    currentCash: portfolio.cash,
    totalValue: portfolio.totalValue,
    totalPnL: portfolio.totalPnl,
    totalPnLPercent: portfolio.totalPnlPercent,
    totalTrades: portfolio.trades.length,
    position: portfolio.position
      ? {
          symbol: portfolio.position.symbol,
          quantity: portfolio.position.quantity,
          avgPrice: portfolio.position.avgPrice,
          currentPrice: portfolio.position.currentPrice,
          unrealizedPnL: portfolio.position.unrealizedPnl,
          unrealizedPnLPercent: portfolio.position.unrealizedPnlPercent,
        }
      : null,
  };

  const jsonContent = JSON.stringify(summary, null, 2);
  downloadFile(jsonContent, 'portfolio_summary.json', 'application/json');
};

// Export analytics report
export const exportAnalyticsReport = (
  portfolio: Portfolio,
  analytics: any
): void => {
  const report = `
=================================================
GOLD TRADING SIMULATOR - ANALYTICS REPORT
=================================================
Generated: ${new Date().toLocaleString()}

PORTFOLIO SUMMARY
-------------------------------------------------
Initial Capital:      $${portfolio.initialCapital.toFixed(2)}
Current Value:        $${portfolio.totalValue.toFixed(2)}
Total P&L:           $${portfolio.totalPnl.toFixed(2)} (${portfolio.totalPnlPercent.toFixed(2)}%)
Cash Available:       $${portfolio.cash.toFixed(2)}

PERFORMANCE METRICS
-------------------------------------------------
Total Trades:         ${analytics.totalTrades}
Win Rate:            ${analytics.winRate}%
Winning Trades:      ${analytics.winningTrades}
Losing Trades:       ${analytics.losingTrades}

Average Win:         $${analytics.avgWin.toFixed(2)}
Average Loss:        $${analytics.avgLoss.toFixed(2)}
Largest Win:         $${analytics.largestWin.toFixed(2)}
Largest Loss:        $${Math.abs(analytics.largestLoss).toFixed(2)}

Profit Factor:       ${analytics.profitFactor === Infinity ? '∞' : analytics.profitFactor.toFixed(2)}
Risk/Reward Ratio:   1:${analytics.riskRewardRatio.toFixed(2)}
Sharpe Ratio:        ${analytics.sharpeRatio.toFixed(2)}
Max Drawdown:        ${analytics.maxDrawdown.toFixed(2)}%

${portfolio.position ? `
CURRENT POSITION
-------------------------------------------------
Symbol:              ${portfolio.position.symbol}
Quantity:            ${portfolio.position.quantity.toFixed(4)} oz
Avg Entry Price:     $${portfolio.position.avgPrice.toFixed(2)}
Current Price:       $${portfolio.position.currentPrice.toFixed(2)}
Unrealized P&L:      $${portfolio.position.unrealizedPnl.toFixed(2)} (${portfolio.position.unrealizedPnlPercent.toFixed(2)}%)
` : ''}

=================================================
END OF REPORT
=================================================
  `.trim();

  downloadFile(report, 'trading_analytics_report.txt', 'text/plain');
};

// Helper function to download file
const downloadFile = (content: string, filename: string, mimeType: string): void => {
  const blob = new Blob([content], { type: mimeType });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
};

// Copy to clipboard
export const copyToClipboard = (text: string): Promise<void> => {
  return navigator.clipboard.writeText(text);
};
