import type { ReactNode } from 'react';
import { useSearchParams } from 'react-router-dom';
import { PageHeader } from '../components/ui/PageHeader';
import { Tabs } from '../components/ui/Tabs';
import { SetupsPanel } from '../components/signals/SetupsPanel';
import { MyTradesPanel } from '../components/signals/MyTradesPanel';
import { BacktestPanel } from '../components/signals/BacktestPanel';
import { EvaluationPanel } from '../components/signals/EvaluationPanel';

const tabs = ['Setups', 'Paper Trades', 'Backtest'] as const;
type Tab = (typeof tabs)[number];

// `track` stays the Paper Trades slug: App.tsx redirects the legacy /performance
// route to ?tab=track, and that is where realized results live.
const SLUG_TO_TAB: Record<string, Tab> = {
  track: 'Paper Trades',
  backtest: 'Backtest',
};
const TAB_TO_SLUG: Record<Tab, string> = {
  Setups: '',
  'Paper Trades': 'track',
  Backtest: 'backtest',
};
const SUBTITLE: Record<Tab, string> = {
  Setups: 'Detected trade setups from the latest scan',
  'Paper Trades': 'What the strategy actually delivered on trades you took',
  Backtest: 'Whether the promoted strategy is worth trading, replayed over history',
};

export default function SignalsPage() {
  const [searchParams, setSearchParams] = useSearchParams();
  const activeTab: Tab = SLUG_TO_TAB[searchParams.get('tab') ?? ''] ?? 'Setups';

  const setTab = (tab: Tab) => {
    const slug = TAB_TO_SLUG[tab];
    setSearchParams(slug ? { tab: slug } : {}, { replace: true });
  };

  const body: Record<Tab, ReactNode> = {
    Setups: <SetupsPanel />,
    'Paper Trades': <MyTradesPanel />,
    // The backtest and the diagnostic that checks it against live outcomes.
    Backtest: (
      <div className="space-y-6">
        <BacktestPanel />
        <EvaluationPanel />
      </div>
    ),
  };

  return (
    <div className="space-y-6 animate-slide-up">
      <PageHeader title="Signals" subtitle={SUBTITLE[activeTab]} />

      <Tabs tabs={tabs} active={activeTab} onChange={setTab} />

      <div className="animate-fade-in" key={activeTab}>
        {body[activeTab]}
      </div>
    </div>
  );
}
