import { useEffect, useState, useCallback } from 'react'
import { BarChart3, Activity, BookOpen, Settings, Brain, LogOut } from 'lucide-react'

// Components
import LiveMarketPanel from './components/LiveMarketPanel'
import MultiChartSSEPanel from './components/MultiChartSSEPanel'
import NotificationCenter from './components/NotificationCenter'
import UserProfileSetup from './components/UserProfileSetup'
import HabitTracker from './components/HabitTracker'
import DailyChecklistPanel from './components/DailyChecklistPanel'
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 SettingsPanel from './components/SettingsPanel'
import PromptTemplatesPanel from './components/PromptTemplatesPanel'
import EquityPerformancePanel from './components/EquityPerformancePanel'
import AdvancedAnalytics from './components/AdvancedAnalytics'

// Types
type MainView = 'Dashboard' | 'Trade' | 'Journal' | 'AICoach' | 'Settings'

interface NavItem {
  id: MainView
  label: string
  icon: React.ReactNode
  description: string
}

// Navigation configuration  
const NAV_ITEMS: NavItem[] = [
  { 
    id: 'Dashboard', 
    label: 'Dashboard', 
    icon: <BarChart3 className="w-5 h-5" />,
    description: 'Market overview & morning prep'
  },
  { 
    id: 'Trade', 
    label: 'Trade', 
    icon: <Activity className="w-5 h-5" />,
    description: 'Live execution & analysis'
  },
  { 
    id: 'Journal', 
    label: 'Journal', 
    icon: <BookOpen className="w-5 h-5" />,
    description: 'Trading journal & analytics'
  },
  { 
    id: 'AICoach', 
    label: 'AI Coach', 
    icon: <Brain className="w-5 h-5" />,
    description: 'AI insights & coaching'
  },
  { 
    id: 'Settings', 
    label: 'Settings', 
    icon: <Settings className="w-5 h-5" />,
    description: 'Preferences & configuration'
  },
]

/**
 * Clean sticky navigation bar
 */
function NavigationBar({ 
  active, 
  onNavigate 
}: { 
  active: MainView
  onNavigate: (view: MainView) => void 
}) {
  return (
    <nav className="sticky top-0 z-40 border-b border-slate-800 bg-slate-950/95 backdrop-blur">
      <div className="max-w-7xl mx-auto px-6 py-3 flex items-center justify-between">
        {/* Branding */}
        <div className="flex items-center gap-3">
          <div className="rounded-lg bg-amber-500/10 p-2">
            <BarChart3 className="w-5 h-5 text-amber-500" />
          </div>
          <div>
            <h1 className="text-sm font-bold text-white">Market Simulator</h1>
            <p className="text-xs text-slate-400">AI-Powered Trading</p>
          </div>
        </div>

        {/* Nav items */}
        <div className="flex items-center gap-1">
          {NAV_ITEMS.map((item) => (
            <button
              key={item.id}
              onClick={() => onNavigate(item.id)}
              title={item.description}
              className={`inline-flex items-center gap-2 px-3 py-2 rounded-lg transition-all text-sm font-medium ${
                active === item.id
                  ? 'bg-amber-500/20 text-amber-200 border border-amber-500/40'
                  : 'text-slate-400 hover:text-slate-200 hover:bg-slate-800/50'
              }`}
            >
              {item.icon}
              <span className="hidden md:inline">{item.label}</span>
            </button>
          ))}
        </div>

        {/* Right side actions */}
        <div className="flex items-center gap-2">
          <NotificationCenter />
          <button
            type="button"
            className="p-2 rounded-lg hover:bg-slate-800 text-slate-400 transition"
            title="Logout"
          >
            <LogOut className="w-4 h-4" />
          </button>
        </div>
      </div>
    </nav>
  )
}

/**
 * Dashboard view - Morning prep and market overview
 */
function DashboardView() {
  return (
    <div className="space-y-6">
      <div className="rounded-lg border border-slate-800 bg-slate-900/50 p-4">
        <h2 className="font-semibold text-white mb-2">Good Morning, Trader</h2>
        <p className="text-sm text-slate-300">
          Review your trading plan for today, check the market conditions, and prepare your checklist.
        </p>
      </div>

      <div className="grid gap-6 xl:grid-cols-[1.4fr,1fr]">
        <div className="space-y-6">
          <DailyTradingPlan currentPrice={4084.99} onPlanUpdate={() => {}} />
          <DailyMarketSummary currentPrice={4084.99} />
        </div>
        <div className="space-y-6">
          <DailyChecklistPanel checklistType="morning" />
          <HabitTracker />
        </div>
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        <AlertsPanel />
        <NewsFeed />
      </div>
    </div>
  )
}

/**
 * Trade view - Live execution cockpit
 */
function TradeView() {
  return (
    <div className="space-y-6">
      <div className="rounded-lg border border-slate-800 bg-slate-900/50 p-4">
        <h2 className="font-semibold text-white mb-2">Live Trading Cockpit</h2>
        <p className="text-sm text-slate-300">
          Execute trades, monitor risk, review AI analysis, and track your portfolio in real-time.
        </p>
      </div>

      <div className="grid gap-6 xl:grid-cols-[1.4fr,1fr]">
        {/* Left side - Analysis & Execution */}
        <div className="space-y-6">
          <LiveMarketPanel />
          <MultiChartSSEPanel />
          <div className="grid gap-6 lg:grid-cols-2">
            {/* Trade controls would go here */}
            <RiskManagement
              currentPrice={4084.99}
              cash={100000}
              position={null}
              trades={[]}
            />
          </div>
          <AIAnalysisPanel analysis={null} isLoading={false} />
        </div>

        {/* Right side - Portfolio & Automation */}
        <div className="space-y-6">
          {/* Portfolio tracker would go here */}
        </div>
      </div>
    </div>
  )
}

/**
 * Journal view - Trading journal and analytics
 */
function JournalView() {
  return (
    <div className="space-y-6">
      <div className="rounded-lg border border-slate-800 bg-slate-900/50 p-4">
        <h2 className="font-semibold text-white mb-2">Trading Journal & Analysis</h2>
        <p className="text-sm text-slate-300">
          Review your trades, track performance, identify patterns, and improve your trading strategy.
        </p>
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        <TradingJournal />
        <EquityPerformancePanel />
      </div>

      <AdvancedAnalytics portfolio={{ cash: 100000, initialCapital: 100000, totalValue: 100000, totalPnl: 0, totalPnlPercent: 0, position: null, trades: [] }} trades={[]} />
    </div>
  )
}

/**
 * AI Coach view - Consolidated AI features and analysis
 */
function AICoachView() {
  return (
    <div className="space-y-6">
      <div className="rounded-lg border border-slate-800 bg-slate-900/50 p-4">
        <h2 className="font-semibold text-white mb-2">Analysis & Insights</h2>
        <p className="text-sm text-slate-300">
          Get AI-powered analysis and insights to improve your trading decisions.
        </p>
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        <AIAnalysisPanel analysis={null} isLoading={false} />
      </div>
    </div>
  )
}

/**
 * Settings view - Configuration and preferences
 */
function SettingsView() {
  return (
    <div className="space-y-6">
      <div className="rounded-lg border border-slate-800 bg-slate-900/50 p-4">
        <h2 className="font-semibold text-white mb-2">Settings & Configuration</h2>
        <p className="text-sm text-slate-300">
          Configure your preferences, manage prompts, and customize your trading experience.
        </p>
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        <SettingsPanel />
        <PromptTemplatesPanel />
      </div>
    </div>
  )
}

/**
 * Main App Component
 */
export default function App() {
  const [activeView, setActiveView] = useState<MainView>('Dashboard')
  const [showProfileSetup, setShowProfileSetup] = useState(false)

  // Check backend status on mount
  useEffect(() => {
    // Status check removed - not critical for UI refactoring
    return () => {}
  }, [])

  // Render active view
  const renderActiveView = useCallback(() => {
    switch (activeView) {
      case 'Dashboard':
        return <DashboardView />
      case 'Trade':
        return <TradeView />
      case 'Journal':
        return <JournalView />
      case 'AICoach':
        return <AICoachView />
      case 'Settings':
        return <SettingsView />
      default:
        return null
    }
  }, [activeView])

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100">
      <NavigationBar active={activeView} onNavigate={setActiveView} />

      {/* Main content */}
      <main className="mx-auto max-w-7xl px-6 py-8">
        {renderActiveView()}
      </main>

      {/* Profile setup modal */}
      {showProfileSetup && (
        <UserProfileSetup
          onClose={() => setShowProfileSetup(false)}
          onSaved={() => {
            setShowProfileSetup(false)
            setActiveView('Dashboard')
          }}
        />
      )}
    </div>
  )
}
