import { useSearch, useNavigate } from '@tanstack/react-router';
import { TradingOverview } from './trading/TradingOverview';
import { PortfolioComposition } from './trading/PortfolioComposition';
import { TradeHistory } from './trading/TradeHistory';
import { PerformanceCharts } from './trading/PerformanceCharts';
import { BacktestPanel } from './trading/BacktestPanel';
import { MicroTradingPanel } from './trading/MicroTradingPanel';
import { NotificationPreferences } from './trading/NotificationPreferences';
import OverrideTradePanel from './trading/OverrideTradePanel';
import { ErrorBoundary } from '../components/ui';

const TABS = [
  { id: 'overview', label: 'Overview' },
  { id: 'portfolio', label: 'Portfolio' },
  { id: 'history', label: 'Trade History' },
  { id: 'performance', label: 'Performance' },
  { id: 'backtest', label: 'Backtest' },
  { id: 'micro', label: 'Micro-Trading' },
  { id: 'notifications', label: 'Notifications' },
  { id: 'override', label: 'Override' },
] as const;

type TabId = (typeof TABS)[number]['id'];

const VALID_TAB_IDS = new Set<string>(TABS.map((t) => t.id));

export function TradingEnginePage() {
  const { tab } = useSearch({ from: '/trading/engine' });
  const navigate = useNavigate();
  const activeTab: TabId = (tab && VALID_TAB_IDS.has(tab) ? tab : 'overview') as TabId;

  const setActiveTab = (newTab: TabId) => {
    navigate({ to: '/trading/engine', search: { tab: newTab }, replace: true });
  };

  return (
    <div className="space-y-4">
      <h1 className="text-xl font-semibold text-gray-100">Trading Engine</h1>

      {/* Tab Navigation */}
      <div className="flex gap-1 overflow-x-auto border-b border-surface-700 pb-px" role="tablist">
        {TABS.map((tab) => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={`whitespace-nowrap rounded-t-md px-3 py-2 text-sm font-medium transition-colors ${
              activeTab === tab.id
                ? 'border-b-2 border-brand-500 text-brand-300'
                : 'text-gray-400 hover:bg-surface-800 hover:text-gray-200'
            }`}
            role="tab"
            aria-selected={activeTab === tab.id}
            aria-controls={`panel-${tab.id}`}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {/* Tab Content */}
      <ErrorBoundary>
        <div role="tabpanel" id={`panel-${activeTab}`}>
          {activeTab === 'overview' && <TradingOverview />}
          {activeTab === 'portfolio' && <PortfolioComposition />}
          {activeTab === 'history' && <TradeHistory />}
          {activeTab === 'performance' && <PerformanceCharts />}
          {activeTab === 'backtest' && <BacktestPanel />}
          {activeTab === 'micro' && <MicroTradingPanel />}
          {activeTab === 'notifications' && <NotificationPreferences />}
          {activeTab === 'override' && <OverrideTradePanel />}
        </div>
      </ErrorBoundary>
    </div>
  );
}
