import React, { useState } from 'react';
import { Plus, TrendingUp, TrendingDown, Calendar, DollarSign, Target, Clock, ArrowLeft, BarChart3, X, Menu } from 'lucide-react';

const TradingJournal = () => {
  const [trades, setTrades] = useState([]);
  const [showForm, setShowForm] = useState(false);
  const [currentStep, setCurrentStep] = useState(0);
  const [accountSize, setAccountSize] = useState(5109.02);
  const [activeTab, setActiveTab] = useState('dashboard');
  
  const [newTrade, setNewTrade] = useState({
    date: '',
    time: '',
    symbol: '',
    session: 'NONE',
    bias: 'NEUTRAL',
    riskPercent: '',
    rrr: '',
    positionSize: '',
    mode: 'BUY',
    entry: '',
    sl: '',
    tp: '',
    close: '',
    whyOpen: '',
    feelings: '',
    whyClose: '',
    confirmation: ''
  });

  const sessions = ['NONE', 'ASIA', 'LONDON', 'NEW YORK'];
  const biases = ['NEUTRAL', 'BULLISH', 'BEARISH'];
  const modes = ['BUY', 'SELL'];

  const formSteps = [
    {
      title: 'Basic Info',
      fields: ['date', 'time', 'symbol', 'session', 'bias', 'mode']
    },
    {
      title: 'Trade Setup',
      fields: ['riskPercent', 'rrr', 'positionSize', 'entry', 'sl', 'tp']
    },
    {
      title: 'Exit & Close',
      fields: ['close', 'whyOpen', 'feelings']
    },
    {
      title: 'Analysis',
      fields: ['whyClose', 'confirmation']
    }
  ];

  const handleInputChange = (field, value) => {
    setNewTrade(prev => ({ ...prev, [field]: value }));
  };

  const calculateResults = (trade) => {
    const entry = parseFloat(trade.entry) || 0;
    const close = parseFloat(trade.close) || 0;
    const positionSize = parseFloat(trade.positionSize) || 0;
    
    let profit = 0;
    if (trade.mode === 'BUY') {
      profit = ((close - entry) / entry) * positionSize * accountSize;
    } else {
      profit = ((entry - close) / entry) * positionSize * accountSize;
    }
    
    const rewardPercent = (profit / accountSize) * 100;
    const actualRRR = trade.mode === 'BUY' ? 
      (close - entry) / (entry - parseFloat(trade.sl || entry)) :
      (entry - close) / (parseFloat(trade.sl || entry) - entry);
    
    return {
      profit: profit.toFixed(2),
      rewardPercent: rewardPercent.toFixed(2),
      actualRRR: actualRRR.toFixed(2),
      result: profit > 0 ? 'WIN' : 'LOSS'
    };
  };

  const addTrade = () => {
    if (!newTrade.date || !newTrade.time || !newTrade.symbol || !newTrade.entry) {
      alert('Please fill in required fields: Date, Time, Symbol, and Entry');
      return;
    }
    
    const results = calculateResults(newTrade);
    const tradeWithResults = {
      ...newTrade,
      id: Date.now(),
      ...results
    };
    
    setTrades(prev => [...prev, tradeWithResults]);
    setAccountSize(prev => prev + parseFloat(results.profit));
    
    // Reset form
    setNewTrade({
      date: '',
      time: '',
      symbol: '',
      session: 'NONE',
      bias: 'NEUTRAL',
      riskPercent: '',
      rrr: '',
      positionSize: '',
      mode: 'BUY',
      entry: '',
      sl: '',
      tp: '',
      close: '',
      whyOpen: '',
      feelings: '',
      whyClose: '',
      confirmation: ''
    });
    setShowForm(false);
    setCurrentStep(0);
    setActiveTab('trades');
  };

  const getStats = () => {
    const wins = trades.filter(t => parseFloat(t.profit) > 0).length;
    const total = trades.length;
    const winRate = total > 0 ? ((wins / total) * 100).toFixed(2) : 0;
    const totalProfit = trades.reduce((sum, t) => sum + parseFloat(t.profit), 0);
    
    return { wins, total, winRate, totalProfit };
  };

  const stats = getStats();

  const nextStep = () => {
    if (currentStep < formSteps.length - 1) {
      setCurrentStep(currentStep + 1);
    }
  };

  const prevStep = () => {
    if (currentStep > 0) {
      setCurrentStep(currentStep - 1);
    }
  };

  const renderFormField = (field) => {
    const commonClasses = "w-full p-4 text-lg border-2 border-gray-200 rounded-xl focus:border-blue-500 focus:outline-none transition-colors";
    
    switch (field) {
      case 'date':
        return (
          <div className="mb-6">
            <label className="block text-sm font-semibold text-gray-700 mb-2">Date *</label>
            <input
              type="date"
              value={newTrade.date}
              onChange={(e) => handleInputChange('date', e.target.value)}
              className={commonClasses}
            />
          </div>
        );
      
      case 'time':
        return (
          <div className="mb-6">
            <label className="block text-sm font-semibold text-gray-700 mb-2">Time *</label>
            <input
              type="time"
              value={newTrade.time}
              onChange={(e) => handleInputChange('time', e.target.value)}
              className={commonClasses}
            />
          </div>
        );
      
      case 'symbol':
        return (
          <div className="mb-6">
            <label className="block text-sm font-semibold text-gray-700 mb-2">Symbol *</label>
            <input
              type="text"
              value={newTrade.symbol}
              onChange={(e) => handleInputChange('symbol', e.target.value.toUpperCase())}
              placeholder="EURUSD, US100, etc."
              className={commonClasses}
            />
          </div>
        );
      
      case 'session':
        return (
          <div className="mb-6">
            <label className="block text-sm font-semibold text-gray-700 mb-2">Session</label>
            <div className="grid grid-cols-2 gap-3">
              {sessions.map(session => (
                <button
                  key={session}
                  type="button"
                  onClick={() => handleInputChange('session', session)}
                  className={`p-3 rounded-xl border-2 transition-colors ${
                    newTrade.session === session
                      ? 'border-blue-500 bg-blue-50 text-blue-700'
                      : 'border-gray-200 bg-white text-gray-700'
                  }`}
                >
                  {session}
                </button>
              ))}
            </div>
          </div>
        );
      
      case 'bias':
        return (
          <div className="mb-6">
            <label className="block text-sm font-semibold text-gray-700 mb-2">Bias</label>
            <div className="grid grid-cols-3 gap-3">
              {biases.map(bias => (
                <button
                  key={bias}
                  type="button"
                  onClick={() => handleInputChange('bias', bias)}
                  className={`p-3 rounded-xl border-2 transition-colors ${
                    newTrade.bias === bias
                      ? 'border-blue-500 bg-blue-50 text-blue-700'
                      : 'border-gray-200 bg-white text-gray-700'
                  }`}
                >
                  {bias}
                </button>
              ))}
            </div>
          </div>
        );
      
      case 'mode':
        return (
          <div className="mb-6">
            <label className="block text-sm font-semibold text-gray-700 mb-2">Mode</label>
            <div className="grid grid-cols-2 gap-3">
              {modes.map(mode => (
                <button
                  key={mode}
                  type="button"
                  onClick={() => handleInputChange('mode', mode)}
                  className={`p-4 rounded-xl border-2 transition-colors ${
                    newTrade.mode === mode
                      ? mode === 'BUY'
                        ? 'border-green-500 bg-green-50 text-green-700'
                        : 'border-red-500 bg-red-50 text-red-700'
                      : 'border-gray-200 bg-white text-gray-700'
                  }`}
                >
                  {mode === 'BUY' ? '📈 BUY' : '📉 SELL'}
                </button>
              ))}
            </div>
          </div>
        );
      
      case 'whyOpen':
      case 'feelings':
      case 'whyClose':
      case 'confirmation':
        return (
          <div className="mb-6">
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              {field === 'whyOpen' ? 'Why Open' : 
               field === 'feelings' ? 'Feelings' : 
               field === 'whyClose' ? 'Why Close' : 'Confirmation'}
            </label>
            <textarea
              value={newTrade[field]}
              onChange={(e) => handleInputChange(field, e.target.value)}
              rows="4"
              className={`${commonClasses} resize-none`}
              placeholder={
                field === 'whyOpen' ? 'Trade setup reasoning...' :
                field === 'feelings' ? 'How you felt during the trade...' :
                field === 'whyClose' ? 'Exit reasoning...' :
                'Trade confirmation details...'
              }
            />
          </div>
        );
      
      default:
        return (
          <div className="mb-6">
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              {field === 'riskPercent' ? 'Risk %' :
               field === 'rrr' ? 'RRR' :
               field === 'positionSize' ? 'Position Size' :
               field === 'entry' ? 'Entry *' :
               field === 'sl' ? 'Stop Loss' :
               field === 'tp' ? 'Take Profit' :
               field === 'close' ? 'Close Price' : field}
            </label>
            <input
              type="number"
              step={field === 'entry' || field === 'sl' || field === 'tp' || field === 'close' ? '0.00001' : '0.01'}
              value={newTrade[field]}
              onChange={(e) => handleInputChange(field, e.target.value)}
              className={commonClasses}
            />
          </div>
        );
    }
  };

  const renderDashboard = () => (
    <div className="p-4 space-y-6">
      {/* Account Overview */}
      <div className="bg-gradient-to-r from-blue-600 to-purple-600 text-white p-6 rounded-2xl">
        <h2 className="text-lg font-semibold mb-2">Account Balance</h2>
        <p className="text-3xl font-bold">${accountSize.toFixed(2)}</p>
        <p className={`text-sm mt-1 ${stats.totalProfit >= 0 ? 'text-green-200' : 'text-red-200'}`}>
          {stats.totalProfit >= 0 ? '+' : ''}${stats.totalProfit.toFixed(2)} Total P&L
        </p>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-2 gap-4">
        <div className="bg-white p-4 rounded-2xl shadow-sm border">
          <div className="flex items-center gap-2 mb-2">
            <TrendingUp className="text-green-600" size={20} />
            <span className="text-sm font-medium text-gray-600">Win Rate</span>
          </div>
          <p className="text-2xl font-bold text-green-600">{stats.winRate}%</p>
        </div>
        
        <div className="bg-white p-4 rounded-2xl shadow-sm border">
          <div className="flex items-center gap-2 mb-2">
            <Target className="text-blue-600" size={20} />
            <span className="text-sm font-medium text-gray-600">Total Trades</span>
          </div>
          <p className="text-2xl font-bold text-blue-600">{stats.total}</p>
        </div>
        
        <div className="bg-white p-4 rounded-2xl shadow-sm border">
          <div className="flex items-center gap-2 mb-2">
            <TrendingUp className="text-green-600" size={20} />
            <span className="text-sm font-medium text-gray-600">Wins</span>
          </div>
          <p className="text-2xl font-bold text-green-600">{stats.wins}</p>
        </div>
        
        <div className="bg-white p-4 rounded-2xl shadow-sm border">
          <div className="flex items-center gap-2 mb-2">
            <TrendingDown className="text-red-600" size={20} />
            <span className="text-sm font-medium text-gray-600">Losses</span>
          </div>
          <p className="text-2xl font-bold text-red-600">{stats.total - stats.wins}</p>
        </div>
      </div>

      {/* Recent Trades */}
      <div className="bg-white rounded-2xl shadow-sm border overflow-hidden">
        <div className="p-4 border-b">
          <h3 className="font-semibold text-gray-800">Recent Trades</h3>
        </div>
        {trades.length === 0 ? (
          <div className="p-8 text-center text-gray-500">
            <Calendar size={48} className="mx-auto mb-4 text-gray-300" />
            <p>No trades yet</p>
          </div>
        ) : (
          <div className="max-h-80 overflow-y-auto">
            {trades.slice(-5).reverse().map((trade) => (
              <div key={trade.id} className="p-4 border-b last:border-b-0">
                <div className="flex justify-between items-start mb-2">
                  <div>
                    <p className="font-semibold text-gray-800">{trade.symbol}</p>
                    <p className="text-sm text-gray-500">{trade.date} {trade.time}</p>
                  </div>
                  <div className="text-right">
                    <p className={`font-semibold ${parseFloat(trade.profit) >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                      ${trade.profit}
                    </p>
                    <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                      trade.result === 'WIN' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                    }`}>
                      {trade.result}
                    </span>
                  </div>
                </div>
                <div className="flex justify-between text-sm text-gray-600">
                  <span>{trade.mode}</span>
                  <span>RRR: {trade.actualRRR}</span>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );

  const renderTrades = () => (
    <div className="p-4">
      {trades.length === 0 ? (
        <div className="text-center py-16">
          <Calendar size={64} className="mx-auto mb-4 text-gray-300" />
          <p className="text-gray-500 text-lg">No trades recorded yet</p>
          <p className="text-gray-400 text-sm">Tap the + button to add your first trade</p>
        </div>
      ) : (
        <div className="space-y-4">
          {trades.map((trade) => (
            <div key={trade.id} className="bg-white rounded-2xl shadow-sm border p-4">
              <div className="flex justify-between items-start mb-3">
                <div>
                  <h3 className="font-bold text-lg text-gray-800">{trade.symbol}</h3>
                  <p className="text-sm text-gray-500">{trade.date} {trade.time}</p>
                  <p className="text-sm text-gray-600">{trade.session}</p>
                </div>
                <div className="text-right">
                  <p className={`text-xl font-bold ${parseFloat(trade.profit) >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                    ${trade.profit}
                  </p>
                  <span className={`px-3 py-1 rounded-full text-xs font-medium ${
                    trade.result === 'WIN' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                  }`}>
                    {trade.result}
                  </span>
                </div>
              </div>
              
              <div className="grid grid-cols-2 gap-4 text-sm mb-3">
                <div>
                  <span className="text-gray-500">Mode:</span>
                  <span className={`ml-2 px-2 py-1 rounded text-xs ${
                    trade.mode === 'BUY' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                  }`}>
                    {trade.mode}
                  </span>
                </div>
                <div>
                  <span className="text-gray-500">RRR:</span>
                  <span className="ml-2 font-medium">{trade.actualRRR}</span>
                </div>
                <div>
                  <span className="text-gray-500">Entry:</span>
                  <span className="ml-2 font-medium">{trade.entry}</span>
                </div>
                <div>
                  <span className="text-gray-500">Close:</span>
                  <span className="ml-2 font-medium">{trade.close}</span>
                </div>
              </div>
              
              {trade.whyOpen && (
                <div className="mt-3 p-3 bg-gray-50 rounded-lg">
                  <p className="text-xs text-gray-500 mb-1">Why Open:</p>
                  <p className="text-sm text-gray-700">{trade.whyOpen}</p>
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );

  if (showForm) {
    return (
      <div className="min-h-screen bg-gray-50">
        {/* Header */}
        <div className="bg-white border-b sticky top-0 z-10">
          <div className="flex items-center justify-between p-4">
            <button
              onClick={currentStep > 0 ? prevStep : () => setShowForm(false)}
              className="p-2 -ml-2"
            >
              <ArrowLeft size={24} className="text-gray-600" />
            </button>
            <div className="text-center flex-1">
              <h1 className="font-semibold text-lg">{formSteps[currentStep].title}</h1>
              <p className="text-sm text-gray-500">Step {currentStep + 1} of {formSteps.length}</p>
            </div>
            <button
              onClick={() => setShowForm(false)}
              className="p-2 -mr-2"
            >
              <X size={24} className="text-gray-600" />
            </button>
          </div>
          
          {/* Progress Bar */}
          <div className="h-1 bg-gray-200">
            <div 
              className="h-1 bg-blue-500 transition-all duration-300"
              style={{ width: `${((currentStep + 1) / formSteps.length) * 100}%` }}
            />
          </div>
        </div>

        {/* Form Content */}
        <div className="p-4">
          <div className="space-y-4">
            {formSteps[currentStep].fields.map(field => (
              <div key={field}>
                {renderFormField(field)}
              </div>
            ))}
          </div>
        </div>

        {/* Bottom Navigation */}
        <div className="fixed bottom-0 left-0 right-0 bg-white border-t p-4">
          <div className="flex gap-3">
            {currentStep > 0 && (
              <button
                onClick={prevStep}
                className="flex-1 py-3 px-4 border border-gray-300 rounded-xl text-gray-700 font-medium"
              >
                Previous
              </button>
            )}
            {currentStep < formSteps.length - 1 ? (
              <button
                onClick={nextStep}
                className="flex-1 py-3 px-4 bg-blue-600 text-white rounded-xl font-medium"
              >
                Next
              </button>
            ) : (
              <button
                onClick={addTrade}
                className="flex-1 py-3 px-4 bg-green-600 text-white rounded-xl font-medium"
              >
                Add Trade
              </button>
            )}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <div className="bg-white border-b sticky top-0 z-10">
        <div className="flex items-center justify-between p-4">
          <h1 className="text-xl font-bold text-gray-800">Trading Journal</h1>
          <button
            onClick={() => setShowForm(true)}
            className="bg-blue-600 text-white p-3 rounded-full shadow-lg"
          >
            <Plus size={24} />
          </button>
        </div>
      </div>

      {/* Content */}
      <div className="pb-20">
        {activeTab === 'dashboard' && renderDashboard()}
        {activeTab === 'trades' && renderTrades()}
      </div>

      {/* Bottom Navigation */}
      <div className="fixed bottom-0 left-0 right-0 bg-white border-t">
        <div className="grid grid-cols-2">
          <button
            onClick={() => setActiveTab('dashboard')}
            className={`flex flex-col items-center p-4 ${
              activeTab === 'dashboard' ? 'text-blue-600' : 'text-gray-400'
            }`}
          >
            <BarChart3 size={24} />
            <span className="text-xs mt-1">Dashboard</span>
          </button>
          <button
            onClick={() => setActiveTab('trades')}
            className={`flex flex-col items-center p-4 ${
              activeTab === 'trades' ? 'text-blue-600' : 'text-gray-400'
            }`}
          >
            <Calendar size={24} />
            <span className="text-xs mt-1">Trades</span>
          </button>
        </div>
      </div>
    </div>
  );
};

export default TradingJournal;