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';

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)}
            className="tab-button"
            data-active={tab === t}
          >
            {t}
          </button>
        ))}
      </div>

      {tab === 'Positions & Orders' && (
        <PositionsTab
          botState={botState}
          onManageHolding={(position, action) => {
            const params = action === 'open-plan' && position.planEntryId
              ? new URLSearchParams({ setupId: position.planEntryId })
              : new URLSearchParams({
                  mode: 'sell',
                  symbol: position.symbol,
                });
            if (action !== 'open-plan' && position.tradeId) params.set('tradeId', position.tradeId);
            navigate(`/plans?${params.toString()}`);
          }}
        />
      )}
      {tab === 'Trade History'      && <HistoryTab botState={botState} />}
    </div>
  );
}
