# ML Dashboard - Ejemplos de Uso

## Importaciones

```typescript
// Importar todos los componentes
import {
  AMDPhaseIndicator,
  PredictionCard,
  SignalsTimeline,
  AccuracyMetrics
} from './modules/ml/components';

// Importar página
import MLDashboard from './modules/ml/pages/MLDashboard';

// Importar tipos
import type { MLSignal, AMDPhase } from './services/mlService';
```

## 1. AMDPhaseIndicator

### Versión Completa

```tsx
import { AMDPhaseIndicator } from './modules/ml/components';

function MyComponent() {
  const amdData = {
    phase: 'accumulation' as const,
    confidence: 0.85,
    phaseDuration: 42,
    nextPhaseProbability: {
      accumulation: 0.15,
      manipulation: 0.65,
      distribution: 0.20,
    },
    keyLevels: {
      support: 42500.00,
      resistance: 44200.00,
    },
  };

  return (
    <AMDPhaseIndicator
      phase={amdData.phase}
      confidence={amdData.confidence}
      phaseDuration={amdData.phaseDuration}
      nextPhaseProbability={amdData.nextPhaseProbability}
      keyLevels={amdData.keyLevels}
    />
  );
}
```

### Versión Compacta (para cards)

```tsx
import { AMDPhaseIndicator } from './modules/ml/components';

function SignalCard() {
  return (
    <div className="card p-4">
      <h3>BTC/USDT Signal</h3>
      <AMDPhaseIndicator
        phase="manipulation"
        confidence={0.72}
        compact={true}  // Versión compacta
      />
    </div>
  );
}
```

## 2. PredictionCard

### Uso Básico

```tsx
import { PredictionCard } from './modules/ml/components';
import type { MLSignal } from './services/mlService';

function SignalsList() {
  const signal: MLSignal = {
    signal_id: 'sig_123',
    symbol: 'BTC/USDT',
    direction: 'long',
    entry_price: 43500.00,
    stop_loss: 42800.00,
    take_profit: 45200.00,
    risk_reward_ratio: 2.4,
    confidence_score: 0.78,
    prob_tp_first: 0.65,
    amd_phase: 'accumulation',
    volatility_regime: 'normal',
    valid_until: '2025-12-09T12:00:00Z',
    created_at: '2025-12-08T10:30:00Z',
  };

  const handleExecute = (sig: MLSignal) => {
    console.log('Executing trade:', sig);
    // Navegar a trading page o abrir modal
    window.location.href = `/trading?symbol=${sig.symbol}&signal=${sig.signal_id}`;
  };

  return (
    <PredictionCard
      signal={signal}
      onExecuteTrade={handleExecute}
      showExecuteButton={true}
    />
  );
}
```

### Grid de Señales

```tsx
import { PredictionCard } from './modules/ml/components';

function SignalsGrid({ signals }: { signals: MLSignal[] }) {
  return (
    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
      {signals.map((signal) => (
        <PredictionCard
          key={signal.signal_id}
          signal={signal}
          onExecuteTrade={(sig) => console.log('Execute:', sig)}
        />
      ))}
    </div>
  );
}
```

## 3. SignalsTimeline

### Timeline Básico

```tsx
import { SignalsTimeline } from './modules/ml/components';

function HistoryPanel() {
  const historicalSignals = [
    {
      signal_id: 'sig_001',
      symbol: 'BTC/USDT',
      direction: 'long' as const,
      entry_price: 42000,
      stop_loss: 41500,
      take_profit: 43500,
      risk_reward_ratio: 3.0,
      confidence_score: 0.85,
      prob_tp_first: 0.70,
      amd_phase: 'accumulation',
      volatility_regime: 'low',
      valid_until: '2025-12-08T12:00:00Z',
      created_at: '2025-12-07T10:00:00Z',
      status: 'success' as const,
      outcome_pnl: 3.57,
    },
    {
      signal_id: 'sig_002',
      symbol: 'ETH/USDT',
      direction: 'short' as const,
      entry_price: 2300,
      stop_loss: 2350,
      take_profit: 2200,
      risk_reward_ratio: 2.0,
      confidence_score: 0.65,
      prob_tp_first: 0.55,
      amd_phase: 'distribution',
      volatility_regime: 'high',
      valid_until: '2025-12-08T18:00:00Z',
      created_at: '2025-12-08T06:00:00Z',
      status: 'failed' as const,
      outcome_pnl: -2.17,
    },
  ];

  return (
    <SignalsTimeline
      signals={historicalSignals}
      maxItems={5}  // Mostrar solo 5
    />
  );
}
```

### Timeline Completo con Scroll

```tsx
import { SignalsTimeline } from './modules/ml/components';

function FullHistory() {
  const [signals, setSignals] = useState([]);

  useEffect(() => {
    // Fetch historical signals
    fetchHistoricalSignals().then(setSignals);
  }, []);

  return (
    <div className="h-screen overflow-y-auto">
      <SignalsTimeline
        signals={signals}
        maxItems={50}  // Mostrar hasta 50
      />
    </div>
  );
}
```

## 4. AccuracyMetrics

### Métricas Completas

```tsx
import { AccuracyMetrics } from './modules/ml/components';

function PerformancePanel() {
  const modelMetrics = {
    overall_accuracy: 68.5,
    win_rate: 62.3,
    total_signals: 156,
    successful_signals: 97,
    failed_signals: 59,
    avg_risk_reward: 2.3,
    avg_confidence: 72,
    best_performing_phase: 'accumulation',
    sharpe_ratio: 1.8,
    profit_factor: 1.7,
  };

  return (
    <AccuracyMetrics
      metrics={modelMetrics}
      period="Last 30 days"
    />
  );
}
```

### Métricas por Periodo

```tsx
import { AccuracyMetrics } from './modules/ml/components';
import { useState } from 'react';

function PerformanceComparison() {
  const [period, setPeriod] = useState('30d');

  const metricsLast30Days = { /* ... */ };
  const metricsLast7Days = { /* ... */ };

  const currentMetrics = period === '30d' ? metricsLast30Days : metricsLast7Days;

  return (
    <div>
      <select value={period} onChange={(e) => setPeriod(e.target.value)}>
        <option value="7d">Last 7 days</option>
        <option value="30d">Last 30 days</option>
        <option value="90d">Last 90 days</option>
      </select>

      <AccuracyMetrics
        metrics={currentMetrics}
        period={`Last ${period.replace('d', ' days')}`}
      />
    </div>
  );
}
```

## 5. Dashboard Completo

### Integración Completa

```tsx
import { useState, useEffect, useCallback } from 'react';
import {
  AMDPhaseIndicator,
  PredictionCard,
  SignalsTimeline,
  AccuracyMetrics,
} from './modules/ml/components';
import { getActiveSignals, getAMDPhase } from './services/mlService';

function CustomMLDashboard() {
  const [signals, setSignals] = useState([]);
  const [amdPhase, setAmdPhase] = useState(null);
  const [loading, setLoading] = useState(true);

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const [signalsData, amdData] = await Promise.all([
        getActiveSignals(),
        getAMDPhase('BTC/USDT'),
      ]);
      setSignals(signalsData);
      setAmdPhase(amdData);
    } catch (error) {
      console.error('Error fetching ML data:', error);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchData, 60000); // Refresh every minute
    return () => clearInterval(interval);
  }, [fetchData]);

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
      {/* Left Column */}
      <div className="lg:col-span-2 space-y-6">
        {/* AMD Phase */}
        {amdPhase && (
          <AMDPhaseIndicator
            phase={amdPhase.phase}
            confidence={amdPhase.confidence}
            phaseDuration={amdPhase.phase_duration_bars}
            nextPhaseProbability={amdPhase.next_phase_probability}
            keyLevels={amdPhase.key_levels}
          />
        )}

        {/* Signals Grid */}
        <div>
          <h2 className="text-xl font-bold mb-4">Active Predictions</h2>
          <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
            {signals.map((signal) => (
              <PredictionCard
                key={signal.signal_id}
                signal={signal}
                onExecuteTrade={(sig) => {
                  console.log('Execute:', sig);
                  // Handle trade execution
                }}
              />
            ))}
          </div>
        </div>

        {/* Timeline */}
        <SignalsTimeline signals={signals} maxItems={10} />
      </div>

      {/* Right Column */}
      <div className="space-y-6">
        <AccuracyMetrics
          metrics={{
            overall_accuracy: 68.5,
            win_rate: 62.3,
            total_signals: 156,
            successful_signals: 97,
            failed_signals: 59,
            avg_risk_reward: 2.3,
            avg_confidence: 72,
            best_performing_phase: 'accumulation',
            sharpe_ratio: 1.8,
            profit_factor: 1.7,
          }}
          period="Last 30 days"
        />
      </div>
    </div>
  );
}
```

## 6. Integración con Trading Page

### Agregar Panel ML a Página Existente

```tsx
import { AMDPhaseIndicator } from './modules/ml/components';
import { getAMDPhase } from './services/mlService';

function TradingPage() {
  const [symbol, setSymbol] = useState('BTC/USDT');
  const [amdPhase, setAmdPhase] = useState(null);

  useEffect(() => {
    getAMDPhase(symbol).then(setAmdPhase);
  }, [symbol]);

  return (
    <div className="grid grid-cols-4 gap-4">
      {/* Chart */}
      <div className="col-span-3">
        <TradingChart symbol={symbol} />
      </div>

      {/* Sidebar with ML info */}
      <div className="space-y-4">
        {amdPhase && (
          <AMDPhaseIndicator
            phase={amdPhase.phase}
            confidence={amdPhase.confidence}
            compact={true}
          />
        )}
        {/* Other sidebar content */}
      </div>
    </div>
  );
}
```

## 7. Uso con React Query

### Fetching Optimizado

```tsx
import { useQuery } from '@tanstack/react-query';
import { getActiveSignals } from './services/mlService';
import { PredictionCard } from './modules/ml/components';

function OptimizedSignalsList() {
  const { data: signals, isLoading, error } = useQuery({
    queryKey: ['ml-signals'],
    queryFn: getActiveSignals,
    refetchInterval: 60000, // Auto-refresh every 60s
    staleTime: 30000,       // Consider data stale after 30s
  });

  if (isLoading) return <div>Loading signals...</div>;
  if (error) return <div>Error loading signals</div>;

  return (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
      {signals?.map((signal) => (
        <PredictionCard
          key={signal.signal_id}
          signal={signal}
        />
      ))}
    </div>
  );
}
```

## 8. Testing Examples

### Component Tests

```tsx
import { render, screen } from '@testing-library/react';
import { AMDPhaseIndicator } from './modules/ml/components';

describe('AMDPhaseIndicator', () => {
  it('renders accumulation phase correctly', () => {
    render(
      <AMDPhaseIndicator
        phase="accumulation"
        confidence={0.85}
      />
    );

    expect(screen.getByText('Accumulation Phase')).toBeInTheDocument();
    expect(screen.getByText('85%')).toBeInTheDocument();
  });

  it('shows compact version', () => {
    const { container } = render(
      <AMDPhaseIndicator
        phase="manipulation"
        confidence={0.70}
        compact={true}
      />
    );

    // Verify compact styling is applied
    expect(container.firstChild).toHaveClass('flex items-center gap-2');
  });
});
```

## 9. Custom Hooks

### useMLSignals Hook

```tsx
import { useState, useEffect, useCallback } from 'react';
import { getActiveSignals, type MLSignal } from './services/mlService';

export function useMLSignals(autoRefresh = true, interval = 60000) {
  const [signals, setSignals] = useState<MLSignal[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchSignals = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await getActiveSignals();
      setSignals(data);
    } catch (err) {
      setError('Failed to fetch signals');
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchSignals();

    if (autoRefresh) {
      const intervalId = setInterval(fetchSignals, interval);
      return () => clearInterval(intervalId);
    }
  }, [fetchSignals, autoRefresh, interval]);

  return { signals, loading, error, refetch: fetchSignals };
}

// Uso
function MyComponent() {
  const { signals, loading, error, refetch } = useMLSignals();

  return (
    <div>
      <button onClick={refetch}>Refresh</button>
      {signals.map(signal => (
        <PredictionCard key={signal.signal_id} signal={signal} />
      ))}
    </div>
  );
}
```

## 10. Estilos Personalizados

### Temas Custom

```tsx
import { AMDPhaseIndicator } from './modules/ml/components';

// Override con className
function CustomStyledIndicator() {
  return (
    <AMDPhaseIndicator
      phase="accumulation"
      confidence={0.85}
      className="shadow-2xl border-2 border-blue-500"
    />
  );
}

// Wrapper con estilos propios
function BlueThemedIndicator() {
  return (
    <div className="bg-gradient-to-br from-blue-900 to-blue-800 p-6 rounded-xl">
      <AMDPhaseIndicator
        phase="accumulation"
        confidence={0.85}
      />
    </div>
  );
}
```

## Notas Importantes

1. **TypeScript**: Todos los componentes están tipados. Usa los tipos exportados.
2. **Error Handling**: Siempre maneja errores de API con try/catch.
3. **Performance**: Usa useCallback para evitar re-renders innecesarios.
4. **Cleanup**: Limpia intervals y subscriptions en useEffect.
5. **Responsive**: Todos los componentes son responsive por defecto.

## Recursos

- [README.md](./README.md) - Documentación completa
- [VALIDATION_CHECKLIST.md](./VALIDATION_CHECKLIST.md) - Testing checklist
- [ML_DASHBOARD_IMPLEMENTATION.md](../ML_DASHBOARD_IMPLEMENTATION.md) - Detalles de implementación
