/**
 * TradeJournalPanel Component
 * Trade review, analysis, and journaling for paper trading
 * OQI-003: Trading y Charts
 */

import React, { useState, useMemo } from 'react';
import {
  BookOpen,
  TrendingUp,
  TrendingDown,
  Calendar,
  Tag,
  MessageSquare,
  Star,
  Filter,
  Search,
  Download,
  BarChart3,
  Target,
  Clock,
  DollarSign,
  Percent,
  ChevronDown,
  ChevronUp,
  Edit3,
  Save,
  X,
  Plus,
  Award,
  AlertTriangle,
  Zap,
} from 'lucide-react';

export interface TradeEntry {
  id: string;
  ticket: number;
  symbol: string;
  type: 'BUY' | 'SELL';
  entryPrice: number;
  exitPrice: number;
  lots: number;
  profit: number;
  profitPercent: number;
  entryTime: string;
  exitTime: string;
  duration: number; // minutes
  stopLoss?: number;
  takeProfit?: number;
  // Journal fields
  notes?: string;
  rating?: 1 | 2 | 3 | 4 | 5;
  tags?: string[];
  strategy?: string;
  setup?: string;
  emotions?: string;
  lessonsLearned?: string;
  screenshots?: string[];
}

interface TradeStats {
  totalTrades: number;
  winningTrades: number;
  losingTrades: number;
  winRate: number;
  totalProfit: number;
  averageWin: number;
  averageLoss: number;
  profitFactor: number;
  largestWin: number;
  largestLoss: number;
  averageRR: number;
  currentStreak: number;
  longestWinStreak: number;
  longestLoseStreak: number;
  averageDuration: number;
}

interface TradeJournalPanelProps {
  trades?: TradeEntry[];
  onTradeUpdate?: (trade: TradeEntry) => void;
  onExportJournal?: (format: 'csv' | 'pdf') => void;
  compact?: boolean;
}

const STRATEGY_TAGS = ['Trend Following', 'Reversal', 'Breakout', 'Scalping', 'Swing', 'Range'];
const SETUP_TAGS = ['Support/Resistance', 'Moving Average', 'RSI Divergence', 'MACD Cross', 'Fibonacci', 'Pattern'];
const EMOTION_TAGS = ['Confident', 'Fearful', 'Greedy', 'Patient', 'Impulsive', 'Disciplined'];

const TradeJournalPanel: React.FC<TradeJournalPanelProps> = ({
  trades = [],
  onTradeUpdate,
  onExportJournal,
  compact = false,
}) => {
  const [selectedTrade, setSelectedTrade] = useState<TradeEntry | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  const [editedNotes, setEditedNotes] = useState('');
  const [editedRating, setEditedRating] = useState<number>(0);
  const [editedTags, setEditedTags] = useState<string[]>([]);
  const [editedStrategy, setEditedStrategy] = useState('');
  const [editedLessons, setEditedLessons] = useState('');
  const [filterSymbol, setFilterSymbol] = useState('');
  const [filterResult, setFilterResult] = useState<'all' | 'wins' | 'losses'>('all');
  const [showStats, setShowStats] = useState(true);

  // Calculate statistics
  const stats: TradeStats = useMemo(() => {
    if (trades.length === 0) {
      return {
        totalTrades: 0,
        winningTrades: 0,
        losingTrades: 0,
        winRate: 0,
        totalProfit: 0,
        averageWin: 0,
        averageLoss: 0,
        profitFactor: 0,
        largestWin: 0,
        largestLoss: 0,
        averageRR: 0,
        currentStreak: 0,
        longestWinStreak: 0,
        longestLoseStreak: 0,
        averageDuration: 0,
      };
    }

    const wins = trades.filter(t => t.profit > 0);
    const losses = trades.filter(t => t.profit < 0);
    const totalWins = wins.reduce((sum, t) => sum + t.profit, 0);
    const totalLosses = Math.abs(losses.reduce((sum, t) => sum + t.profit, 0));

    // Calculate streaks
    let currentStreak = 0;
    let longestWinStreak = 0;
    let longestLoseStreak = 0;
    let tempWinStreak = 0;
    let tempLoseStreak = 0;

    const sortedTrades = [...trades].sort((a, b) =>
      new Date(b.exitTime).getTime() - new Date(a.exitTime).getTime()
    );

    sortedTrades.forEach((trade, idx) => {
      if (trade.profit > 0) {
        tempWinStreak++;
        tempLoseStreak = 0;
        if (tempWinStreak > longestWinStreak) longestWinStreak = tempWinStreak;
        if (idx === 0) currentStreak = tempWinStreak;
      } else {
        tempLoseStreak++;
        tempWinStreak = 0;
        if (tempLoseStreak > longestLoseStreak) longestLoseStreak = tempLoseStreak;
        if (idx === 0) currentStreak = -tempLoseStreak;
      }
    });

    return {
      totalTrades: trades.length,
      winningTrades: wins.length,
      losingTrades: losses.length,
      winRate: (wins.length / trades.length) * 100,
      totalProfit: trades.reduce((sum, t) => sum + t.profit, 0),
      averageWin: wins.length > 0 ? totalWins / wins.length : 0,
      averageLoss: losses.length > 0 ? totalLosses / losses.length : 0,
      profitFactor: totalLosses > 0 ? totalWins / totalLosses : totalWins,
      largestWin: wins.length > 0 ? Math.max(...wins.map(t => t.profit)) : 0,
      largestLoss: losses.length > 0 ? Math.min(...losses.map(t => t.profit)) : 0,
      averageRR: losses.length > 0 && wins.length > 0
        ? (totalWins / wins.length) / (totalLosses / losses.length) : 0,
      currentStreak,
      longestWinStreak,
      longestLoseStreak,
      averageDuration: trades.reduce((sum, t) => sum + t.duration, 0) / trades.length,
    };
  }, [trades]);

  // Filter trades
  const filteredTrades = useMemo(() => {
    return trades.filter(trade => {
      if (filterSymbol && !trade.symbol.toLowerCase().includes(filterSymbol.toLowerCase())) {
        return false;
      }
      if (filterResult === 'wins' && trade.profit <= 0) return false;
      if (filterResult === 'losses' && trade.profit >= 0) return false;
      return true;
    });
  }, [trades, filterSymbol, filterResult]);

  const handleEditTrade = (trade: TradeEntry) => {
    setSelectedTrade(trade);
    setEditedNotes(trade.notes || '');
    setEditedRating(trade.rating || 0);
    setEditedTags(trade.tags || []);
    setEditedStrategy(trade.strategy || '');
    setEditedLessons(trade.lessonsLearned || '');
    setIsEditing(true);
  };

  const handleSaveTrade = () => {
    if (!selectedTrade) return;

    const updatedTrade: TradeEntry = {
      ...selectedTrade,
      notes: editedNotes,
      rating: editedRating as 1 | 2 | 3 | 4 | 5,
      tags: editedTags,
      strategy: editedStrategy,
      lessonsLearned: editedLessons,
    };

    onTradeUpdate?.(updatedTrade);
    setIsEditing(false);
    setSelectedTrade(updatedTrade);
  };

  const handleToggleTag = (tag: string) => {
    if (editedTags.includes(tag)) {
      setEditedTags(editedTags.filter(t => t !== tag));
    } else {
      setEditedTags([...editedTags, tag]);
    }
  };

  const formatDuration = (minutes: number) => {
    if (minutes < 60) return `${minutes}m`;
    if (minutes < 1440) return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
    return `${Math.floor(minutes / 1440)}d ${Math.floor((minutes % 1440) / 60)}h`;
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  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">
          <BookOpen className="w-5 h-5 text-blue-400" />
          <div>
            <h3 className="font-semibold text-white">Trade Journal</h3>
            <p className="text-xs text-gray-500">{trades.length} trades recorded</p>
          </div>
        </div>

        <div className="flex items-center gap-2">
          <button
            onClick={() => onExportJournal?.('csv')}
            className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
            title="Export CSV"
          >
            <Download className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* Stats Summary */}
      {showStats && (
        <div className="grid grid-cols-4 gap-3 mb-4">
          <div className="p-3 bg-gray-900/50 rounded-lg text-center">
            <div className={`text-lg font-bold ${stats.totalProfit >= 0 ? 'text-green-400' : 'text-red-400'}`}>
              ${stats.totalProfit.toFixed(2)}
            </div>
            <div className="text-xs text-gray-500">Total P&L</div>
          </div>
          <div className="p-3 bg-gray-900/50 rounded-lg text-center">
            <div className="text-lg font-bold text-white">{stats.winRate.toFixed(1)}%</div>
            <div className="text-xs text-gray-500">Win Rate</div>
          </div>
          <div className="p-3 bg-gray-900/50 rounded-lg text-center">
            <div className="text-lg font-bold text-white">{stats.profitFactor.toFixed(2)}</div>
            <div className="text-xs text-gray-500">Profit Factor</div>
          </div>
          <div className="p-3 bg-gray-900/50 rounded-lg text-center">
            <div className={`text-lg font-bold ${stats.currentStreak >= 0 ? 'text-green-400' : 'text-red-400'}`}>
              {stats.currentStreak >= 0 ? `+${stats.currentStreak}` : stats.currentStreak}
            </div>
            <div className="text-xs text-gray-500">Streak</div>
          </div>
        </div>
      )}

      {/* Extended Stats */}
      {!compact && showStats && (
        <div className="grid grid-cols-3 gap-3 mb-4 p-3 bg-gray-900/50 rounded-lg">
          <div className="flex items-center gap-2">
            <Award className="w-4 h-4 text-green-400" />
            <div>
              <div className="text-xs text-gray-500">Best Trade</div>
              <div className="text-green-400 font-medium">${stats.largestWin.toFixed(2)}</div>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <AlertTriangle className="w-4 h-4 text-red-400" />
            <div>
              <div className="text-xs text-gray-500">Worst Trade</div>
              <div className="text-red-400 font-medium">${stats.largestLoss.toFixed(2)}</div>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <Clock className="w-4 h-4 text-blue-400" />
            <div>
              <div className="text-xs text-gray-500">Avg Duration</div>
              <div className="text-white font-medium">{formatDuration(stats.averageDuration)}</div>
            </div>
          </div>
        </div>
      )}

      {/* Filters */}
      <div className="flex items-center gap-2 mb-4">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
          <input
            type="text"
            value={filterSymbol}
            onChange={(e) => setFilterSymbol(e.target.value)}
            placeholder="Filter by symbol..."
            className="w-full pl-10 pr-4 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white text-sm focus:outline-none focus:border-blue-500"
          />
        </div>
        <select
          value={filterResult}
          onChange={(e) => setFilterResult(e.target.value as 'all' | 'wins' | 'losses')}
          className="px-3 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white text-sm"
        >
          <option value="all">All</option>
          <option value="wins">Wins</option>
          <option value="losses">Losses</option>
        </select>
      </div>

      {/* Trades List */}
      {filteredTrades.length === 0 ? (
        <div className="text-center py-8">
          <BookOpen className="w-10 h-10 text-gray-600 mx-auto mb-2" />
          <p className="text-gray-400">No trades to journal</p>
          <p className="text-gray-500 text-xs mt-1">Complete some trades to start journaling</p>
        </div>
      ) : (
        <div className="space-y-2 max-h-[300px] overflow-y-auto">
          {filteredTrades.map((trade) => (
            <div
              key={trade.id}
              onClick={() => setSelectedTrade(selectedTrade?.id === trade.id ? null : trade)}
              className={`p-3 bg-gray-900/50 rounded-lg border cursor-pointer transition-all ${
                selectedTrade?.id === trade.id
                  ? 'border-blue-500/50 bg-blue-500/5'
                  : 'border-gray-700 hover:border-gray-600'
              }`}
            >
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <div className={`p-1.5 rounded ${trade.type === 'BUY' ? 'bg-green-500/20' : 'bg-red-500/20'}`}>
                    {trade.type === 'BUY' ? (
                      <TrendingUp className="w-4 h-4 text-green-400" />
                    ) : (
                      <TrendingDown className="w-4 h-4 text-red-400" />
                    )}
                  </div>
                  <div>
                    <div className="flex items-center gap-2">
                      <span className="font-medium text-white">{trade.symbol}</span>
                      <span className="text-xs text-gray-500">{trade.lots} lots</span>
                      {trade.rating && (
                        <div className="flex items-center">
                          {Array.from({ length: trade.rating }).map((_, i) => (
                            <Star key={i} className="w-3 h-3 text-yellow-400 fill-current" />
                          ))}
                        </div>
                      )}
                    </div>
                    <div className="text-xs text-gray-500">
                      {formatDate(trade.exitTime)} • {formatDuration(trade.duration)}
                    </div>
                  </div>
                </div>
                <div className="text-right">
                  <div className={`font-mono font-medium ${trade.profit >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                    {trade.profit >= 0 ? '+' : ''}{trade.profit.toFixed(2)}
                  </div>
                  <div className={`text-xs ${trade.profit >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                    {trade.profitPercent >= 0 ? '+' : ''}{trade.profitPercent.toFixed(2)}%
                  </div>
                </div>
              </div>

              {/* Tags */}
              {trade.tags && trade.tags.length > 0 && (
                <div className="flex flex-wrap gap-1 mt-2">
                  {trade.tags.map((tag) => (
                    <span key={tag} className="px-2 py-0.5 bg-gray-800 text-gray-400 rounded text-xs">
                      {tag}
                    </span>
                  ))}
                </div>
              )}

              {/* Expanded Details */}
              {selectedTrade?.id === trade.id && !isEditing && (
                <div className="mt-3 pt-3 border-t border-gray-700">
                  <div className="grid grid-cols-2 gap-3 text-xs mb-3">
                    <div>
                      <span className="text-gray-500">Entry:</span>
                      <span className="text-white ml-2">{trade.entryPrice.toFixed(5)}</span>
                    </div>
                    <div>
                      <span className="text-gray-500">Exit:</span>
                      <span className="text-white ml-2">{trade.exitPrice.toFixed(5)}</span>
                    </div>
                    {trade.stopLoss && (
                      <div>
                        <span className="text-gray-500">SL:</span>
                        <span className="text-red-400 ml-2">{trade.stopLoss.toFixed(5)}</span>
                      </div>
                    )}
                    {trade.takeProfit && (
                      <div>
                        <span className="text-gray-500">TP:</span>
                        <span className="text-green-400 ml-2">{trade.takeProfit.toFixed(5)}</span>
                      </div>
                    )}
                  </div>

                  {trade.strategy && (
                    <div className="text-xs mb-2">
                      <span className="text-gray-500">Strategy:</span>
                      <span className="text-blue-400 ml-2">{trade.strategy}</span>
                    </div>
                  )}

                  {trade.notes && (
                    <div className="text-xs mb-2">
                      <span className="text-gray-500">Notes:</span>
                      <p className="text-gray-300 mt-1">{trade.notes}</p>
                    </div>
                  )}

                  {trade.lessonsLearned && (
                    <div className="text-xs mb-2">
                      <span className="text-gray-500">Lessons:</span>
                      <p className="text-yellow-400 mt-1">{trade.lessonsLearned}</p>
                    </div>
                  )}

                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      handleEditTrade(trade);
                    }}
                    className="flex items-center gap-1 px-3 py-1.5 bg-blue-600 hover:bg-blue-500 text-white rounded text-xs mt-2"
                  >
                    <Edit3 className="w-3 h-3" />
                    Edit Journal Entry
                  </button>
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      {/* Edit Modal */}
      {isEditing && selectedTrade && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70">
          <div className="w-full max-w-lg bg-gray-800 rounded-xl shadow-2xl max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between p-4 border-b border-gray-700">
              <h3 className="font-semibold text-white">Edit Journal Entry</h3>
              <button
                onClick={() => setIsEditing(false)}
                className="p-2 text-gray-400 hover:text-white"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="p-4 space-y-4">
              {/* Trade Info */}
              <div className="flex items-center gap-3 p-3 bg-gray-900/50 rounded-lg">
                <div className={`p-2 rounded ${selectedTrade.type === 'BUY' ? 'bg-green-500/20' : 'bg-red-500/20'}`}>
                  {selectedTrade.type === 'BUY' ? (
                    <TrendingUp className="w-5 h-5 text-green-400" />
                  ) : (
                    <TrendingDown className="w-5 h-5 text-red-400" />
                  )}
                </div>
                <div>
                  <div className="font-medium text-white">{selectedTrade.symbol}</div>
                  <div className={`text-sm ${selectedTrade.profit >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                    {selectedTrade.profit >= 0 ? '+' : ''}{selectedTrade.profit.toFixed(2)}
                  </div>
                </div>
              </div>

              {/* Rating */}
              <div>
                <label className="block text-sm text-gray-400 mb-2">Trade Rating</label>
                <div className="flex gap-1">
                  {[1, 2, 3, 4, 5].map((rating) => (
                    <button
                      key={rating}
                      onClick={() => setEditedRating(rating)}
                      className="p-1"
                    >
                      <Star
                        className={`w-6 h-6 ${
                          rating <= editedRating ? 'text-yellow-400 fill-current' : 'text-gray-600'
                        }`}
                      />
                    </button>
                  ))}
                </div>
              </div>

              {/* Strategy */}
              <div>
                <label className="block text-sm text-gray-400 mb-2">Strategy</label>
                <div className="flex flex-wrap gap-2">
                  {STRATEGY_TAGS.map((tag) => (
                    <button
                      key={tag}
                      onClick={() => setEditedStrategy(tag)}
                      className={`px-3 py-1 rounded text-xs ${
                        editedStrategy === tag
                          ? 'bg-blue-600 text-white'
                          : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
                      }`}
                    >
                      {tag}
                    </button>
                  ))}
                </div>
              </div>

              {/* Tags */}
              <div>
                <label className="block text-sm text-gray-400 mb-2">Tags</label>
                <div className="flex flex-wrap gap-2">
                  {[...SETUP_TAGS, ...EMOTION_TAGS].map((tag) => (
                    <button
                      key={tag}
                      onClick={() => handleToggleTag(tag)}
                      className={`px-3 py-1 rounded text-xs ${
                        editedTags.includes(tag)
                          ? 'bg-blue-600 text-white'
                          : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
                      }`}
                    >
                      {tag}
                    </button>
                  ))}
                </div>
              </div>

              {/* Notes */}
              <div>
                <label className="block text-sm text-gray-400 mb-2">Notes</label>
                <textarea
                  value={editedNotes}
                  onChange={(e) => setEditedNotes(e.target.value)}
                  placeholder="What was your thought process?"
                  className="w-full px-3 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white text-sm focus:outline-none focus:border-blue-500 resize-none"
                  rows={3}
                />
              </div>

              {/* Lessons Learned */}
              <div>
                <label className="block text-sm text-gray-400 mb-2">Lessons Learned</label>
                <textarea
                  value={editedLessons}
                  onChange={(e) => setEditedLessons(e.target.value)}
                  placeholder="What would you do differently?"
                  className="w-full px-3 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white text-sm focus:outline-none focus:border-blue-500 resize-none"
                  rows={2}
                />
              </div>
            </div>

            <div className="flex items-center gap-3 p-4 border-t border-gray-700">
              <button
                onClick={() => setIsEditing(false)}
                className="flex-1 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-lg font-medium"
              >
                Cancel
              </button>
              <button
                onClick={handleSaveTrade}
                className="flex-1 flex items-center justify-center gap-2 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg font-medium"
              >
                <Save className="w-4 h-4" />
                Save Entry
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default TradeJournalPanel;
