import { useState, useEffect } from 'react';
import { BookOpen, Plus, Calendar, TrendingUp, TrendingDown, Smile, Meh, Frown, Search, Filter } from 'lucide-react';

interface JournalEntry {
  id: string;
  date: string;
  timestamp: number;
  tradeId?: string;
  action: 'BUY' | 'SELL';
  price: number;
  quantity: number;
  pnl?: number;
  setupQuality: 1 | 2 | 3 | 4 | 5;
  emotionalState: 'confident' | 'neutral' | 'anxious' | 'fearful' | 'greedy';
  planFollowed: boolean;
  entryReason: string;
  exitReason?: string;
  marketConditions: string;
  lessonsLearned: string;
  tags: string[];
}

interface TradingJournalProps {
  onAddEntry?: (entry: JournalEntry) => void;
}

export default function TradingJournal({ onAddEntry }: TradingJournalProps) {
  const [entries, setEntries] = useState<JournalEntry[]>(() => {
    const stored = localStorage.getItem('trading-journal');
    if (stored) {
      try {
        return JSON.parse(stored);
      } catch {
        return [];
      }
    }
    return [];
  });

  const [isAddingEntry, setIsAddingEntry] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterEmotion, setFilterEmotion] = useState<string>('all');
  const [filterPnL, setFilterPnL] = useState<'all' | 'winners' | 'losers'>('all');

  const [newEntry, setNewEntry] = useState<Partial<JournalEntry>>({
    action: 'BUY',
    price: 0,
    quantity: 0,
    setupQuality: 3,
    emotionalState: 'neutral',
    planFollowed: true,
    entryReason: '',
    marketConditions: '',
    lessonsLearned: '',
    tags: [],
  });

  useEffect(() => {
    localStorage.setItem('trading-journal', JSON.stringify(entries));
  }, [entries]);

  const handleAddEntry = () => {
    const entry: JournalEntry = {
      id: Date.now().toString(),
      date: new Date().toDateString(),
      timestamp: Date.now(),
      ...newEntry as any,
    };

    setEntries(prev => [entry, ...prev]);
    
    if (onAddEntry) {
      onAddEntry(entry);
    }

    // Reset form
    setNewEntry({
      action: 'BUY',
      price: 0,
      quantity: 0,
      setupQuality: 3,
      emotionalState: 'neutral',
      planFollowed: true,
      entryReason: '',
      marketConditions: '',
      lessonsLearned: '',
      tags: [],
    });
    
    setIsAddingEntry(false);
  };

  const filteredEntries = entries.filter(entry => {
    // Search filter
    if (searchTerm) {
      const searchLower = searchTerm.toLowerCase();
      const matchesSearch = 
        entry.entryReason.toLowerCase().includes(searchLower) ||
        entry.exitReason?.toLowerCase().includes(searchLower) ||
        entry.marketConditions.toLowerCase().includes(searchLower) ||
        entry.lessonsLearned.toLowerCase().includes(searchLower) ||
        entry.tags.some(tag => tag.toLowerCase().includes(searchLower));
      
      if (!matchesSearch) return false;
    }

    // Emotion filter
    if (filterEmotion !== 'all' && entry.emotionalState !== filterEmotion) {
      return false;
    }

    // P&L filter
    if (filterPnL === 'winners' && (!entry.pnl || entry.pnl <= 0)) {
      return false;
    }
    if (filterPnL === 'losers' && (!entry.pnl || entry.pnl >= 0)) {
      return false;
    }

    return true;
  });

  const getEmotionIcon = (emotion: string) => {
    switch (emotion) {
      case 'confident':
      case 'greedy':
        return <Smile className="w-5 h-5 text-green-500" />;
      case 'neutral':
        return <Meh className="w-5 h-5 text-gray-400" />;
      case 'anxious':
      case 'fearful':
        return <Frown className="w-5 h-5 text-red-500" />;
      default:
        return <Meh className="w-5 h-5 text-gray-400" />;
    }
  };

  const stats = {
    totalEntries: entries.length,
    avgSetupQuality: entries.length > 0
      ? (entries.reduce((sum, e) => sum + e.setupQuality, 0) / entries.length).toFixed(1)
      : '0',
    planFollowedPercent: entries.length > 0
      ? ((entries.filter(e => e.planFollowed).length / entries.length) * 100).toFixed(0)
      : '0',
  };

  return (
    <div className="h-full flex flex-col">
      {/* Header */}
      <div className="mb-4 pb-4 border-b border-gray-700">
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-3">
            <BookOpen className="w-6 h-6 text-gold-500" />
            <div>
              <h3 className="text-lg font-semibold">Trading Journal</h3>
              <p className="text-xs text-gray-400">{stats.totalEntries} entries recorded</p>
            </div>
          </div>
          <button
            onClick={() => setIsAddingEntry(!isAddingEntry)}
            className="btn-primary text-sm flex items-center gap-2"
          >
            <Plus className="w-4 h-4" />
            New Entry
          </button>
        </div>

        {/* Quick Stats */}
        <div className="grid grid-cols-3 gap-3">
          <div className="p-2 bg-dark-hover rounded text-center">
            <div className="text-xs text-gray-400">Entries</div>
            <div className="text-lg font-bold text-gold-500">{stats.totalEntries}</div>
          </div>
          <div className="p-2 bg-dark-hover rounded text-center">
            <div className="text-xs text-gray-400">Avg Setup</div>
            <div className="text-lg font-bold text-blue-500">{stats.avgSetupQuality}/5</div>
          </div>
          <div className="p-2 bg-dark-hover rounded text-center">
            <div className="text-xs text-gray-400">Plan Followed</div>
            <div className="text-lg font-bold text-green-500">{stats.planFollowedPercent}%</div>
          </div>
        </div>
      </div>

      {/* Add Entry Form */}
      {isAddingEntry && (
        <div className="mb-4 p-4 bg-dark-hover rounded-lg border border-gray-700">
          <h4 className="font-semibold mb-3">New Journal Entry</h4>
          
          <div className="grid grid-cols-2 gap-3 mb-3">
            <div>
              <label className="block text-xs text-gray-400 mb-1">Action</label>
              <select
                value={newEntry.action}
                onChange={(e) => setNewEntry({ ...newEntry, action: e.target.value as any })}
                className="w-full px-3 py-2 bg-dark-bg border border-gray-700 rounded text-sm"
              >
                <option value="BUY">BUY</option>
                <option value="SELL">SELL</option>
              </select>
            </div>
            <div>
              <label className="block text-xs text-gray-400 mb-1">Price</label>
              <input
                type="number"
                step="0.01"
                value={newEntry.price}
                onChange={(e) => setNewEntry({ ...newEntry, price: Number(e.target.value) })}
                className="w-full px-3 py-2 bg-dark-bg border border-gray-700 rounded text-sm"
              />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-3 mb-3">
            <div>
              <label className="block text-xs text-gray-400 mb-1">Setup Quality (1-5)</label>
              <div className="flex gap-1">
                {[1, 2, 3, 4, 5].map(rating => (
                  <button
                    key={rating}
                    onClick={() => setNewEntry({ ...newEntry, setupQuality: rating as any })}
                    className={`flex-1 py-2 rounded border-2 transition-colors ${
                      (newEntry.setupQuality || 0) >= rating
                        ? 'border-gold-500 bg-gold-500/20 text-gold-500'
                        : 'border-gray-700 text-gray-500'
                    }`}
                  >
                    ★
                  </button>
                ))}
              </div>
            </div>
            <div>
              <label className="block text-xs text-gray-400 mb-1">Emotional State</label>
              <select
                value={newEntry.emotionalState}
                onChange={(e) => setNewEntry({ ...newEntry, emotionalState: e.target.value as any })}
                className="w-full px-3 py-2 bg-dark-bg border border-gray-700 rounded text-sm"
              >
                <option value="confident">Confident</option>
                <option value="neutral">Neutral</option>
                <option value="anxious">Anxious</option>
                <option value="fearful">Fearful</option>
                <option value="greedy">Greedy</option>
              </select>
            </div>
          </div>

          <div className="mb-3">
            <label className="block text-xs text-gray-400 mb-1">Entry Reason</label>
            <textarea
              value={newEntry.entryReason}
              onChange={(e) => setNewEntry({ ...newEntry, entryReason: e.target.value })}
              className="w-full px-3 py-2 bg-dark-bg border border-gray-700 rounded text-sm"
              rows={2}
              placeholder="Why did you enter this trade?"
            />
          </div>

          <div className="mb-3">
            <label className="block text-xs text-gray-400 mb-1">Market Conditions</label>
            <textarea
              value={newEntry.marketConditions}
              onChange={(e) => setNewEntry({ ...newEntry, marketConditions: e.target.value })}
              className="w-full px-3 py-2 bg-dark-bg border border-gray-700 rounded text-sm"
              rows={2}
              placeholder="Describe market conditions..."
            />
          </div>

          <div className="mb-3">
            <label className="block text-xs text-gray-400 mb-1">Lessons Learned</label>
            <textarea
              value={newEntry.lessonsLearned}
              onChange={(e) => setNewEntry({ ...newEntry, lessonsLearned: e.target.value })}
              className="w-full px-3 py-2 bg-dark-bg border border-gray-700 rounded text-sm"
              rows={2}
              placeholder="What did you learn?"
            />
          </div>

          <div className="mb-3">
            <label className="flex items-center gap-2 text-sm">
              <input
                type="checkbox"
                checked={newEntry.planFollowed}
                onChange={(e) => setNewEntry({ ...newEntry, planFollowed: e.target.checked })}
                className="rounded"
              />
              <span>I followed my trading plan</span>
            </label>
          </div>

          <div className="flex gap-2">
            <button onClick={handleAddEntry} className="btn-primary text-sm flex-1">
              Save Entry
            </button>
            <button
              onClick={() => setIsAddingEntry(false)}
              className="btn-secondary text-sm"
            >
              Cancel
            </button>
          </div>
        </div>
      )}

      {/* Filters */}
      <div className="mb-4 space-y-2">
        <div className="flex gap-2">
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              placeholder="Search entries..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-3 py-2 bg-dark-bg border border-gray-700 rounded-lg text-sm"
            />
          </div>
          <button className="p-2 bg-dark-bg border border-gray-700 rounded-lg hover:bg-dark-hover">
            <Filter className="w-4 h-4" />
          </button>
        </div>
        
        <div className="flex gap-2">
          <select
            value={filterEmotion}
            onChange={(e) => setFilterEmotion(e.target.value)}
            className="flex-1 px-3 py-2 bg-dark-bg border border-gray-700 rounded text-sm"
          >
            <option value="all">All Emotions</option>
            <option value="confident">Confident</option>
            <option value="neutral">Neutral</option>
            <option value="anxious">Anxious</option>
            <option value="fearful">Fearful</option>
            <option value="greedy">Greedy</option>
          </select>
          
          <select
            value={filterPnL}
            onChange={(e) => setFilterPnL(e.target.value as any)}
            className="flex-1 px-3 py-2 bg-dark-bg border border-gray-700 rounded text-sm"
          >
            <option value="all">All Trades</option>
            <option value="winners">Winners Only</option>
            <option value="losers">Losers Only</option>
          </select>
        </div>
      </div>

      {/* Journal Entries */}
      <div className="flex-1 overflow-y-auto space-y-3">
        {filteredEntries.length === 0 ? (
          <div className="text-center py-8 text-gray-400">
            <BookOpen className="w-12 h-12 mx-auto mb-3 opacity-50" />
            <p>No journal entries found</p>
            <p className="text-sm">Start documenting your trading journey</p>
          </div>
        ) : (
          filteredEntries.map(entry => (
            <div
              key={entry.id}
              className="p-4 bg-dark-hover rounded-lg border border-gray-700 hover:border-gray-600 transition-colors"
            >
              {/* Entry Header */}
              <div className="flex items-start justify-between mb-3">
                <div className="flex items-center gap-3">
                  {entry.action === 'BUY' ? (
                    <TrendingUp className="w-5 h-5 text-green-500" />
                  ) : (
                    <TrendingDown className="w-5 h-5 text-red-500" />
                  )}
                  <div>
                    <div className="font-semibold">
                      {entry.action} @ ${entry.price.toFixed(2)}
                    </div>
                    <div className="text-xs text-gray-400 flex items-center gap-2">
                      <Calendar className="w-3 h-3" />
                      {new Date(entry.timestamp).toLocaleString()}
                    </div>
                  </div>
                </div>
                <div className="text-right">
                  {entry.pnl !== undefined && (
                    <div className={`font-bold ${entry.pnl > 0 ? 'text-green-500' : 'text-red-500'}`}>
                      {entry.pnl > 0 ? '+' : ''}${entry.pnl.toFixed(2)}
                    </div>
                  )}
                  <div className="flex items-center gap-1 justify-end mt-1">
                    {[...Array(entry.setupQuality)].map((_, i) => (
                      <span key={i} className="text-gold-500 text-xs">★</span>
                    ))}
                  </div>
                </div>
              </div>

              {/* Emotional State & Plan Followed */}
              <div className="flex items-center gap-4 mb-3 text-sm">
                <div className="flex items-center gap-2">
                  {getEmotionIcon(entry.emotionalState)}
                  <span className="text-gray-400 capitalize">{entry.emotionalState}</span>
                </div>
                <div className={`flex items-center gap-1 ${entry.planFollowed ? 'text-green-500' : 'text-red-500'}`}>
                  {entry.planFollowed ? '✓' : '✗'} Plan {entry.planFollowed ? 'Followed' : 'Deviated'}
                </div>
              </div>

              {/* Entry Details */}
              {entry.entryReason && (
                <div className="mb-2">
                  <div className="text-xs text-gray-500 font-medium mb-1">Entry Reason:</div>
                  <div className="text-sm text-gray-300">{entry.entryReason}</div>
                </div>
              )}

              {entry.exitReason && (
                <div className="mb-2">
                  <div className="text-xs text-gray-500 font-medium mb-1">Exit Reason:</div>
                  <div className="text-sm text-gray-300">{entry.exitReason}</div>
                </div>
              )}

              {entry.marketConditions && (
                <div className="mb-2">
                  <div className="text-xs text-gray-500 font-medium mb-1">Market Conditions:</div>
                  <div className="text-sm text-gray-300">{entry.marketConditions}</div>
                </div>
              )}

              {entry.lessonsLearned && (
                <div className="mb-2">
                  <div className="text-xs text-gray-500 font-medium mb-1">Lessons Learned:</div>
                  <div className="text-sm text-gray-300 italic">{entry.lessonsLearned}</div>
                </div>
              )}

              {/* Tags */}
              {entry.tags.length > 0 && (
                <div className="flex flex-wrap gap-1 mt-2">
                  {entry.tags.map((tag, i) => (
                    <span
                      key={i}
                      className="px-2 py-1 bg-blue-500/20 text-blue-500 text-xs rounded"
                    >
                      {tag}
                    </span>
                  ))}
                </div>
              )}
            </div>
          ))
        )}
      </div>
    </div>
  );
}
