import { Suspense, lazy, useState } from 'react';
import { useAppContext } from '../context/AppContext';
import { SignalsTab } from '../tabs/SignalsTab';
import { BacktestTab } from '../tabs/BacktestTab';
import { MyStrategiesTab } from '../tabs/MyStrategiesTab';
import { VisualRuleBuilder, type VisualRule } from '../components/strategy/VisualRuleBuilder';
import { createTradeProfile } from '../lib/profileApi';
import { BacktestRunnerPanel } from '../backtest/components/BacktestRunnerPanel';

type ResearchTab = 'Strategies' | 'Visual Builder' | 'Code Editor' | 'Signals' | 'Backtesting';

const CodeStrategyEditor = lazy(() =>
  import('../components/strategy/CodeStrategyEditor').then(module => ({ default: module.CodeStrategyEditor })),
);

function buildVisualStrategyConfig(rules: VisualRule[]) {
  return {
    type: 'visual',
    version: 1,
    rules: rules.map(r => ({
      indicator:    r.indicator,
      condition:    r.condition,
      value:        r.value,
      action:       r.action,
      quantity:     r.quantity,
      quantityType: r.quantityType,
    })),
  };
}

// Sub-tab pill styles
function SubTab({
  label, active, onClick,
}: { label: string; active: boolean; onClick: () => void }) {
  return (
    <button
      onClick={onClick}
      style={{
        padding: '8px 16px',
        border: 'none',
        borderBottom: active ? '2px solid #2563EB' : '2px solid transparent',
        background: 'transparent',
        color: active ? '#2563EB' : '#6B7280',
        fontSize: 13,
        fontWeight: active ? 700 : 500,
        cursor: 'pointer',
        marginBottom: -1,
        transition: 'all 0.15s',
        fontFamily: 'inherit',
      }}
    >
      {label}
    </button>
  );
}

export function ResearchView() {
  const { botState, connected, showBacktestTab, isAdmin, activeSymbol } = useAppContext();
  const [tab, setTab] = useState<ResearchTab>('Strategies');
  const [visualBacktestRules, setVisualBacktestRules] = useState<VisualRule[] | null>(null);

  const tabs: ResearchTab[] = [
    'Strategies',
    'Visual Builder',
    'Code Editor',
    ...(isAdmin ? ['Signals' as ResearchTab] : []),
    ...(showBacktestTab ? ['Backtesting' as ResearchTab] : []),
  ];

  // Save a visual-builder strategy via the canonical createTradeProfile helper.
  // Backend `saveTradeProfileForUser` expects the TradeProfilePayload shape:
  //   { name, symbols, allocated_capital, risk_per_trade_percent, is_active,
  //     strategy_config: { ... } }
  // Visual rules go inside strategy_config.rules so the strategy engine can
  // route to the visual interpreter (alongside the existing rule-based engine).
  const handleSaveVisualStrategy = async (name: string, rules: VisualRule[]) => {
    const symbol = activeSymbol || Object.keys(botState.symbols)[0] || 'SPY';
    const totalCapital = botState.settings?.totalCapital ?? 1000;
    const riskPct      = botState.settings?.riskPerTrade ?? 1;

    await createTradeProfile({
      name,
      symbols: symbol,
      allocated_capital: totalCapital,
      risk_per_trade_percent: riskPct,
      is_active: false, // user activates explicitly from MyStrategiesTab
      strategy_config: buildVisualStrategyConfig(rules),
    });
  };

  const visualBuilderSymbol = activeSymbol || Object.keys(botState.symbols)[0] || 'SPY';
  const initialCapitalUsd = botState.settings?.totalCapital ?? 1000;

  return (
    <div>
      <h2 style={{ fontSize: 22, fontWeight: 800, color: '#111827', margin: '0 0 20px' }}>Research</h2>

      <div style={{
        display: 'flex', gap: 4, marginBottom: 20,
        borderBottom: '1px solid #E5E7EB',
      }}>
        {tabs.map(t => (
          <SubTab key={t} label={t} active={tab === t} onClick={() => setTab(t)} />
        ))}
      </div>

      {tab === 'Strategies' && (
        <MyStrategiesTab
          botState={botState}
          alerts={botState.alerts}
          previewAsCustomer={false}
        />
      )}

      {tab === 'Visual Builder' && (
        <div>
          <div style={{ marginBottom: 16 }}>
            <div style={{ fontSize: 15, fontWeight: 700, color: '#111827', marginBottom: 4 }}>
              Visual Rule Builder
            </div>
            <div style={{ fontSize: 13, color: '#6B7280' }}>
              Build a trading strategy by composing IF/THEN rules. Drag rows to reorder. Click "Save Strategy" to store it.
            </div>
          </div>
          <VisualRuleBuilder
            symbol={visualBuilderSymbol}
            onSave={handleSaveVisualStrategy}
            onBacktest={showBacktestTab ? (rules) => setVisualBacktestRules(rules.map(rule => ({ ...rule }))) : undefined}
          />
          {showBacktestTab && visualBacktestRules && (
            <div style={{ marginTop: 20 }}>
              <BacktestRunnerPanel
                strategyConfig={buildVisualStrategyConfig(visualBacktestRules)}
                symbols={[visualBuilderSymbol]}
                initialCapitalUsd={initialCapitalUsd}
                title={`Backtest: Visual Strategy (${visualBuilderSymbol})`}
                onClose={() => setVisualBacktestRules(null)}
              />
            </div>
          )}
        </div>
      )}

      {tab === 'Code Editor' && (
        <div>
          <div style={{ marginBottom: 16 }}>
            <div style={{ fontSize: 15, fontWeight: 700, color: '#111827', marginBottom: 4 }}>
              Code Strategy Editor
            </div>
            <div style={{ fontSize: 13, color: '#6B7280' }}>
              Write a custom strategy function in JavaScript. Click "Run Backtest" to test it against historical data.
            </div>
          </div>
          <Suspense fallback={<CodeStrategyEditorFallback />}>
            <CodeStrategyEditor
              symbol={activeSymbol || Object.keys(botState.symbols)[0] || 'SPY'}
              allocatedCapital={botState.settings?.totalCapital ?? 1000}
              riskPerTradePercent={botState.settings?.riskPerTrade ?? 1}
            />
          </Suspense>
        </div>
      )}

      {tab === 'Signals' && (
        <SignalsTab botState={botState} connected={connected} />
      )}

      {tab === 'Backtesting' && (
        <BacktestTab previewAsCustomer={false} />
      )}
    </div>
  );
}

function CodeStrategyEditorFallback() {
  return (
    <div
      role="status"
      aria-label="Loading code strategy editor"
      style={{
        minHeight: 420,
        border: '1px solid #E5E7EB',
        borderRadius: 12,
        background: 'linear-gradient(135deg, #F8FAFC, #EEF2FF)',
        color: '#4B5563',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        fontSize: 13,
        fontWeight: 700,
      }}
    >
      Loading code strategy editor…
    </div>
  );
}
