import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAppContext } from '../context/AppContext';
import { PositionsTab } from '../tabs/PositionsTab';
import { HistoryTab } from '../tabs/HistoryTab';
import { PageHeader } from '../components/ui/page-header';
import { Button } from '../components/ui/Primitives';
import { buildCreateExitPlanUrl, buildPlanDrillInUrl } from './tradePlansRoutes';

const TABS = ['Positions & Orders', 'Trade History'] as const;
type Tab = typeof TABS[number];

export function PortfolioView() {
  const { botState } = useAppContext();
  const navigate = useNavigate();
  const [tab, setTab] = useState<Tab>('Positions & Orders');

  return (
    <div>
      <PageHeader
        title="Portfolio"
        description="Review live positions, order activity, and completed trades in one consistent operational view."
      />

      <div className="tab-strip" style={{ marginBottom: 20 }}>
        {TABS.map(t => (
          <Button
            key={t}
            onClick={() => setTab(t)}
            variant="ghost"
            size="sm"
            className="tab-button"
            data-active={tab === t}
          >
            {t}
          </Button>
        ))}
      </div>

      {tab === 'Positions & Orders' && (
        <PositionsTab
          botState={botState}
          onManageHolding={(position, action) => {
            const target = action === 'open-plan' && position.planEntryId
              ? buildPlanDrillInUrl(position.planEntryId)
              : buildCreateExitPlanUrl(position.symbol, position.tradeId);
            navigate(target);
          }}
        />
      )}
      {tab === 'Trade History'      && <HistoryTab botState={botState} />}
    </div>
  );
}
