import { useEffect, useState } from 'react'
import LiveMarketPanel from './components/LiveMarketPanel'
import MultiChartSSEPanel from './components/MultiChartSSEPanel'
import AccountPositionsPanel from './components/AccountPositionsPanel'
import SettingsPanel from './components/SettingsPanel'
import PromptTemplatesPanel from './components/PromptTemplatesPanel'
import { statusApi } from './services/api'

// Phase 1: Daily Helper Components
import NotificationCenter from './components/NotificationCenter'
import UserProfileSetup from './components/UserProfileSetup'
import HabitTracker from './components/HabitTracker'
import DailyChecklistPanel from './components/DailyChecklistPanel'

// Analysis & Decision Components
import AIAnalysisPanel from './components/AIAnalysisPanel'
import DailyTradingPlan from './components/DailyTradingPlan'
import RiskManagement from './components/RiskManagement'
import TradingJournal from './components/TradingJournal'
import DailyMarketSummary from './components/DailyMarketSummary'
import NewsFeed from './components/NewsFeed'
import AlertsPanel from './components/AlertsPanel'
import AdvancedAnalytics from './components/AdvancedAnalytics'
import ManualTradeLogger from './components/ManualTradeLogger'

function Tabs({ tabs, active, onChange }: { tabs: string[]; active: string; onChange: (t: string) => void }) {
  return (
    <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
      {tabs.map(t => (
        <button key={t} className={`btn ${active === t ? 'bg-blue-600 text-white' : 'bg-dark-surface text-gray-300'}`} onClick={() => onChange(t)}>
          {t}
        </button>
      ))}
    </div>
  )
}

export default function App() {
  const [activeTab, setActiveTab] = useState<'Analysis Hub' | 'Daily Prep' | 'Journal & Review' | 'Live Charts' | 'Account' | 'Settings' | 'Prompts'>('Analysis Hub')
  const [backendStatus, setBackendStatus] = useState<any>(null)
  const [showProfileSetup, setShowProfileSetup] = useState(false)
  
  // Trading state for logged trades
  const [loggedTrades, setLoggedTrades] = useState<any[]>([])
  const [currentPrice, setCurrentPrice] = useState<number>(4084.99)
  const [aiAnalysis, setAiAnalysis] = useState<any>(null)
  const [isAnalyzing, setIsAnalyzing] = useState(false)

  useEffect(() => {
    let mounted = true
    ;(async () => {
      try {
        const s = await statusApi.getStatus()
        if (mounted) setBackendStatus(s)
      } catch (e) {
        // ignore
      }
    })()
    return () => { mounted = false }
  }, [])
  
  // Simulate price updates (in real app, this would come from WebSocket/SSE)
  useEffect(() => {
    const interval = setInterval(() => {
      setCurrentPrice(prev => {
        const change = (Math.random() - 0.5) * 8 // Realistic tick size for gold at ~$4000 level
        return Number((prev + change).toFixed(2))
      })
    }, 3000)
    return () => clearInterval(interval)
  }, [])

  const tabs = ['Analysis Hub', 'Daily Prep', 'Journal & Review', 'Live Charts', 'Account', 'Settings', 'Prompts']
  
  // Load logged trades from localStorage
  useEffect(() => {
    const stored = localStorage.getItem('logged-trades')
    if (stored) {
      try {
        setLoggedTrades(JSON.parse(stored))
      } catch (e) {
        console.error('Failed to load logged trades:', e)
      }
    }
  }, [])
  
  // Handle new trade logged
  const handleTradeLogged = (trade: any) => {
    setLoggedTrades([...loggedTrades, trade])
  }
  
  const handleAIAnalysis = async () => {
    setIsAnalyzing(true)
    // Simulate AI analysis
    setTimeout(() => {
      const mockAnalysis = {
        recommendation: Math.random() > 0.5 ? 'BUY' : 'SELL',
        confidence: Math.floor(Math.random() * 30 + 60),
        riskLevel: 'MEDIUM',
        reasoning: 'Based on technical analysis and market sentiment, the current market conditions suggest...',
        supportResistance: {
          support: [currentPrice - 20, currentPrice - 40],
          resistance: [currentPrice + 20, currentPrice + 40]
        }
      }
      setAiAnalysis(mockAnalysis)
      setIsAnalyzing(false)
    }, 2000)
  }

  return (
    <div className="min-h-screen bg-dark-bg p-6">
      <div className="max-w-[1400px] mx-auto">
        <header className="mb-6">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-2xl font-bold text-gold-500">Assistant Market Simulator</h1>
              <p className="text-gray-400 text-sm">AI-Powered Trading with Daily Helper</p>
            </div>
            <div className="flex items-center gap-4">
              <NotificationCenter />
              <div className="text-sm text-gray-400">
                {backendStatus ? (
                  <span>API: {backendStatus.app?.name} v{backendStatus.app?.version}</span>
                ) : (
                  <span>Checking API…</span>
                )}
              </div>
            </div>
          </div>
        </header>

        <Tabs tabs={tabs} active={activeTab} onChange={(t) => setActiveTab(t as any)} />

        {/* ANALYSIS HUB - Pre-Trade Analysis & Trade Logging */}
        {activeTab === 'Analysis Hub' && (
          <div style={{ display: 'grid', gap: 16 }}>
            <div className="bg-blue-500/10 border border-blue-500/30 rounded-lg p-4">
              <h3 className="text-lg font-semibold mb-2">🎯 Analysis Hub</h3>
              <p className="text-sm text-gray-300">
                <strong>Workflow:</strong> Analyze → Plan on platform (MT5/TradingView) → Execute there → Log trade here → Monitor & Journal
              </p>
            </div>
            
            {/* Analysis Tools */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(450px, 1fr))', gap: 16 }}>
              {/* AI Analysis - Get recommendation BEFORE trading */}
              <div>
                <AIAnalysisPanel analysis={aiAnalysis} isLoading={isAnalyzing} />
                <button
                  onClick={handleAIAnalysis}
                  className="btn-primary w-full mt-4"
                  disabled={isAnalyzing}
                >
                  {isAnalyzing ? 'Analyzing...' : '🤖 Get AI Analysis'}
                </button>
              </div>
              
              {/* Risk Calculator - Calculate position size BEFORE trading */}
              <RiskManagement
                currentPrice={currentPrice}
                cash={100000}
                position={null}
                trades={loggedTrades}
              />
            </div>
            
            {/* Trade Logger - Log trades from external platform */}
            <ManualTradeLogger onTradeLogged={handleTradeLogged} />
            
            {/* Current Price Reference */}
            <div className="card">
              <h3 className="text-lg font-semibold mb-4">📊 Current Market Price</h3>
              <div className="grid grid-cols-3 gap-4">
                <div className="bg-dark-bg rounded-lg p-4 text-center">
                  <div className="text-sm text-gray-400 mb-1">XAU/USD</div>
                  <div className="text-3xl font-bold text-gold-500">${currentPrice.toFixed(2)}</div>
                  <div className="text-xs text-green-500 mt-1">Live Price</div>
                </div>
                <div className="bg-dark-bg rounded-lg p-4">
                  <div className="text-xs text-gray-400">24h High</div>
                  <div className="text-xl font-semibold text-green-500">${(currentPrice + 15).toFixed(2)}</div>
                </div>
                <div className="bg-dark-bg rounded-lg p-4">
                  <div className="text-xs text-gray-400">24h Low</div>
                  <div className="text-xl font-semibold text-red-500">${(currentPrice - 12).toFixed(2)}</div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* DAILY PREP - Morning Routine */}
        {activeTab === 'Daily Prep' && (
          <div style={{ display: 'grid', gap: 16 }}>
            <div className="bg-green-500/10 border border-green-500/30 rounded-lg p-4">
              <h3 className="text-lg font-semibold mb-2">🌅 Daily Preparation</h3>
              <p className="text-sm text-gray-300">
                Start your day here: Review market, check news, create trading plan
              </p>
            </div>
            
            {/* Pre-Market Section */}
            <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 16 }}>
              <DailyMarketSummary currentPrice={currentPrice} />
              <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                <button
                  onClick={() => setShowProfileSetup(true)}
                  className="bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded transition-colors"
                >
                  ⚙️ Setup Profile
                </button>
                <AlertsPanel />
              </div>
            </div>
            
            {/* Daily Workflow */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(350px, 1fr))', gap: 16 }}>
              <DailyChecklistPanel checklistType="morning" />
              <NewsFeed />
            </div>
            
            {/* Trading Plan */}
            <DailyTradingPlan currentPrice={currentPrice} />
          </div>
        )}
        
        {/* JOURNAL & REVIEW - Post-Trade Analysis */}
        {activeTab === 'Journal & Review' && (
          <div style={{ display: 'grid', gap: 16 }}>
            <div className="bg-purple-500/10 border border-purple-500/30 rounded-lg p-4">
              <h3 className="text-lg font-semibold mb-2">📖 Journal & Review</h3>
              <p className="text-sm text-gray-300">
                Document trades, track performance, identify patterns, improve strategy
              </p>
            </div>
            
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              <TradingJournal />
              <HabitTracker />
            </div>
            
            <AdvancedAnalytics 
              portfolio={{ cash: 100000, initialCapital: 100000, totalValue: 100000, totalPnl: 0, totalPnlPercent: 0, position: null, trades: loggedTrades }}
              trades={loggedTrades}
            />
          </div>
        )}

        {/* LIVE CHARTS - Technical Analysis */}
        {activeTab === 'Live Charts' && (
          <div style={{ display: 'grid', gap: 16 }}>
            <div className="bg-orange-500/10 border border-orange-500/30 rounded-lg p-4">
              <h3 className="text-lg font-semibold mb-2">📈 Live Charts</h3>
              <p className="text-sm text-gray-300">
                Technical analysis with live streaming charts
              </p>
            </div>
            <LiveMarketPanel />
            <MultiChartSSEPanel />
          </div>
        )}

        {activeTab === 'Account' && <AccountPositionsPanel />}

        {activeTab === 'Settings' && <SettingsPanel />}
        {activeTab === 'Prompts' && <PromptTemplatesPanel />}

        {showProfileSetup && (
          <UserProfileSetup
            onClose={() => setShowProfileSetup(false)}
            onSaved={() => {
              // Profile saved successfully
            }}
          />
        )}

        {activeTab === 'Settings' && <SettingsPanel />}
        {activeTab === 'Prompts' && <PromptTemplatesPanel />}
      </div>
    </div>
  )
}
