import { useCallback, useEffect, useState } from 'react';
import { BacktestConfiguration } from './components/BacktestConfiguration';
import { BacktestControls } from './components/BacktestControls';
import { BacktestResults } from './components/BacktestResults';
import { useBacktest } from './hooks/useBacktest';
import type { BacktestConfig, BacktestResult as LocalBacktestResult } from './types/backtest.types';

export function BacktestPage() {
  const {
    backtest,
    results,
    isLoading,
    isPolling,
    error,
    createBacktest,
    cancelBacktest,
    reset,
  } = useBacktest();
  
  // Local state to bridge between the API format and the existing UI components
  const [config, setConfig] = useState<BacktestConfig | null>(null);
  const [adaptedResults, setAdaptedResults] = useState<LocalBacktestResult | null>(null);
  
  // Adapt the backtest status from API format to local format
  const status = backtest ? 
    (backtest.status === 'pending' ? 'configured' :
     backtest.status === 'running' ? 'running' :
     backtest.status === 'completed' ? 'completed' :
     backtest.status === 'failed' ? 'error' :
     backtest.status === 'cancelled' ? 'stopped' : 'idle') : 'idle';
  
  // Current time is not available in the new API, so we'll estimate it based on progress
  const currentTime = null;
  
  // No adaptation needed - results are already in the correct format
  useEffect(() => {
    setAdaptedResults(results);
  }, [results]);
  
  const handleConfigSubmit = useCallback(async (newConfig: BacktestConfig) => {
    setConfig(newConfig);
    setAdaptedResults(null);
    
    // Convert local config to API format
    await createBacktest({
      strategy: newConfig.strategy,
      symbols: newConfig.symbols,
      startDate: newConfig.startDate.toISOString().split('T')[0],
      endDate: newConfig.endDate.toISOString().split('T')[0],
      initialCapital: newConfig.initialCapital,
      config: {
        commission: newConfig.commission,
        slippage: newConfig.slippage,
        speedMultiplier: newConfig.speedMultiplier,
      },
    });
  }, [createBacktest]);
  
  const handleStart = useCallback(() => {
    // Backtest starts automatically after creation in the new API
    // Nothing to do here
  }, []);
  
  const handlePause = useCallback(() => {
    // Pause not supported in current API
    console.warn('Pause not supported in current API');
  }, []);
  
  const handleResume = useCallback(() => {
    // Resume not supported in current API
    console.warn('Resume not supported in current API');
  }, []);
  
  const handleStop = useCallback(async () => {
    await cancelBacktest();
  }, [cancelBacktest]);
  
  const handleStep = useCallback(() => {
    // Step not supported in current API
    console.warn('Step not supported in current API');
  }, []);

  return (
    <div className="flex flex-col h-full space-y-6">
      <div className="flex-shrink-0">
        <h1 className="text-lg font-bold text-text-primary mb-2">Backtest Strategy</h1>
        <p className="text-text-secondary mb-6 text-sm">
          Test your trading strategies against historical data to evaluate performance and risk.
        </p>
      </div>

      {error && (
        <div className="bg-error/10 border border-error text-error px-4 py-3 rounded-lg text-sm">
          {error}
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 flex-1 min-h-0">
        <div className="lg:col-span-1 space-y-4">
          <BacktestConfiguration 
            onSubmit={handleConfigSubmit}
            disabled={status === 'running' || isLoading || isPolling}
          />
          
          {config && (
            <BacktestControls
              status={status}
              onStart={handleStart}
              onPause={handlePause}
              onResume={handleResume}
              onStop={handleStop}
              onStep={handleStep}
              currentTime={currentTime}
              startTime={config.startDate.getTime()}
              endTime={config.endDate.getTime()}
            />
          )}
        </div>

        <div className="lg:col-span-2">
          <BacktestResults
            status={status}
            results={adaptedResults}
            currentTime={currentTime}
          />
        </div>
      </div>
    </div>
  );
}