import { useState, type FormEvent } from 'react';
import { PnLChart } from '../components/charts/PnLChart';
import { ComponentErrorBoundary } from '../components/common/ComponentErrorBoundary';
import { useStartBacktest, useBacktestStatus, useBacktestResults } from '../hooks/useApi';
import { BacktestStatus } from '../gen/fxt_trading_pb';

interface BacktestValidationErrors {
  symbol?: string;
  dateRange?: string;
}

export function BacktestingDashboard() {
  const [strategy, setStrategy] = useState('ml_ensemble');
  const [symbol, setSymbol] = useState('ES.FUT');
  const [startDate, setStartDate] = useState('2025-01-01');
  const [endDate, setEndDate] = useState('2025-12-31');
  const [validationErrors, setValidationErrors] = useState<BacktestValidationErrors>({});

  const [activeBacktestId, setActiveBacktestId] = useState<string | null>(null);

  const startBacktest = useStartBacktest();

  const backtestStatusQuery = useBacktestStatus(activeBacktestId);

  const isCompleted = backtestStatusQuery.data?.status === BacktestStatus.COMPLETED;
  const backtestResults = useBacktestResults(activeBacktestId, isCompleted);

  const hasValidationErrors = Object.keys(validationErrors).length > 0;

  function clearFieldError(field: keyof BacktestValidationErrors) {
    setValidationErrors((prev) => {
      const next = { ...prev };
      delete next[field];
      return next;
    });
  }

  function handleSubmit(e: FormEvent) {
    e.preventDefault();

    const errors: BacktestValidationErrors = {};

    if (!symbol.trim()) {
      errors.symbol = 'Symbol is required';
    } else if (!/^[A-Z0-9.]+$/i.test(symbol)) {
      errors.symbol = 'Symbol must be alphanumeric (dots allowed)';
    }

    if (startDate && endDate && startDate >= endDate) {
      errors.dateRange = 'Start date must be before end date';
    }

    setValidationErrors(errors);
    if (Object.keys(errors).length > 0) return;

    startBacktest.mutate(
      { strategy, symbol, startDate, endDate },
      { onSuccess: (data) => setActiveBacktestId(data.backtestId) },
    );
  }

  // Map BacktestStatus enum to display strings
  function statusLabel(status: BacktestStatus | undefined): string {
    switch (status) {
      case BacktestStatus.RUNNING: return 'running';
      case BacktestStatus.COMPLETED: return 'completed';
      case BacktestStatus.FAILED: return 'failed';
      case BacktestStatus.QUEUED: return 'queued';
      case BacktestStatus.CANCELLED: return 'cancelled';
      default: return 'unknown';
    }
  }

  function statusColorClass(status: BacktestStatus | undefined): string {
    switch (status) {
      case BacktestStatus.COMPLETED: return 'bg-green-500/20 text-[var(--color-green)]';
      case BacktestStatus.FAILED: return 'bg-red-500/20 text-[var(--color-red)]';
      default: return 'bg-blue-500/20 text-[var(--color-accent)]';
    }
  }

  // Adapt equity curve from proto to PnLChart shape
  const equityCurveData = backtestResults.data?.equityCurve?.map((p) => ({
    date: new Date(Number(p.timestampUnixNanos) / 1_000_000).toISOString().slice(0, 10),
    pnl: p.equity,
  }));

  // Adapt trades from proto to display shape
  const trades = backtestResults.data?.trades ?? [];

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Start Form */}
        <div className="rounded border border-[var(--color-border)] bg-[var(--color-bg-card)]">
          <div className="px-3 py-1.5 border-b border-[var(--color-border)]">
            <span className="text-sm font-medium">New Backtest</span>
          </div>
          <form onSubmit={handleSubmit} className="p-3 space-y-3">
            <div>
              <label htmlFor="bt-strategy" className="block text-xs text-[var(--color-text-secondary)] mb-1">
                Strategy
              </label>
              <select
                id="bt-strategy"
                value={strategy}
                onChange={(e) => setStrategy(e.target.value)}
                className="w-full px-2 py-1.5 text-sm rounded border border-[var(--color-border)] bg-[var(--color-bg-primary)] text-[var(--color-text-primary)] outline-none"
              >
                <option value="ml_ensemble">ML Ensemble</option>
                <option value="dqn">DQN Only</option>
                <option value="ppo">PPO Only</option>
                <option value="tft">TFT Only</option>
                <option value="mamba2">Mamba2 Only</option>
              </select>
            </div>
            <div>
              <label htmlFor="bt-symbol" className="block text-xs text-[var(--color-text-secondary)] mb-1">
                Symbol
              </label>
              <input
                id="bt-symbol"
                type="text"
                value={symbol}
                onChange={(e) => {
                  setSymbol(e.target.value);
                  clearFieldError('symbol');
                }}
                className={`w-full px-2 py-1.5 text-sm rounded border bg-[var(--color-bg-primary)] text-[var(--color-text-primary)] outline-none ${
                  validationErrors.symbol
                    ? 'border-[var(--color-red)]'
                    : 'border-[var(--color-border)] focus:border-[var(--color-accent)]'
                }`}
              />
              {validationErrors.symbol && (
                <p className="text-xs text-[var(--color-red)] mt-0.5" role="alert">{validationErrors.symbol}</p>
              )}
            </div>
            <div className="grid grid-cols-2 gap-2">
              <div>
                <label htmlFor="bt-start-date" className="block text-xs text-[var(--color-text-secondary)] mb-1">
                  Start Date
                </label>
                <input
                  id="bt-start-date"
                  type="date"
                  value={startDate}
                  onChange={(e) => {
                    setStartDate(e.target.value);
                    clearFieldError('dateRange');
                  }}
                  className={`w-full px-2 py-1.5 text-sm rounded border bg-[var(--color-bg-primary)] text-[var(--color-text-primary)] outline-none ${
                    validationErrors.dateRange
                      ? 'border-[var(--color-red)]'
                      : 'border-[var(--color-border)] focus:border-[var(--color-accent)]'
                  }`}
                />
              </div>
              <div>
                <label htmlFor="bt-end-date" className="block text-xs text-[var(--color-text-secondary)] mb-1">
                  End Date
                </label>
                <input
                  id="bt-end-date"
                  type="date"
                  value={endDate}
                  onChange={(e) => {
                    setEndDate(e.target.value);
                    clearFieldError('dateRange');
                  }}
                  className={`w-full px-2 py-1.5 text-sm rounded border bg-[var(--color-bg-primary)] text-[var(--color-text-primary)] outline-none ${
                    validationErrors.dateRange
                      ? 'border-[var(--color-red)]'
                      : 'border-[var(--color-border)] focus:border-[var(--color-accent)]'
                  }`}
                />
              </div>
            </div>
            {validationErrors.dateRange && (
              <p className="text-xs text-[var(--color-red)] mt-0.5" role="alert">{validationErrors.dateRange}</p>
            )}
            <button
              type="submit"
              disabled={startBacktest.isPending || hasValidationErrors}
              className="w-full py-2 text-sm font-medium rounded bg-[var(--color-accent)] text-white hover:bg-blue-600 disabled:opacity-50"
            >
              {startBacktest.isPending ? 'Starting...' : 'Start Backtest'}
            </button>
            {startBacktest.isSuccess && (
              <p className="text-xs text-[var(--color-green)]">
                Backtest started: {startBacktest.data.backtestId}
              </p>
            )}
            {startBacktest.isError && (
              <p className="text-xs text-[var(--color-red)]" role="alert">
                {startBacktest.error.message}
              </p>
            )}
          </form>
        </div>

        {/* Active Backtests */}
        <div className="rounded border border-[var(--color-border)] bg-[var(--color-bg-card)]">
          <div className="px-3 py-1.5 border-b border-[var(--color-border)]">
            <span className="text-sm font-medium">Active Backtests</span>
          </div>
          {backtestStatusQuery.data ? (
            <div className="p-3 space-y-2">
              <div className="flex items-center justify-between text-sm">
                <span className="font-mono">{backtestStatusQuery.data.backtestId.slice(0, 8)}</span>
                <span className={`text-xs px-1.5 py-0.5 rounded ${statusColorClass(backtestStatusQuery.data.status)}`}>
                  {statusLabel(backtestStatusQuery.data.status)}
                </span>
              </div>
              <div className="text-xs text-[var(--color-text-secondary)]">
                {strategy} / {symbol}
              </div>
              {backtestStatusQuery.data.status === BacktestStatus.RUNNING && (
                <div className="w-full bg-[var(--color-bg-primary)] rounded-full h-1.5">
                  <div
                    className="bg-[var(--color-accent)] h-1.5 rounded-full transition-all"
                    style={{ width: `${backtestStatusQuery.data.progressPercentage.toFixed(0)}%` }}
                    role="progressbar"
                    aria-valuenow={Math.round(backtestStatusQuery.data.progressPercentage)}
                    aria-valuemin={0}
                    aria-valuemax={100}
                  />
                </div>
              )}
            </div>
          ) : (
            <div className="p-4 text-sm text-[var(--color-text-secondary)] text-center">
              No active backtests
            </div>
          )}
        </div>
      </div>

      {/* Equity Curve */}
      <div className="h-64 rounded border border-[var(--color-border)] bg-[var(--color-bg-card)]">
        <ComponentErrorBoundary name="Equity Curve">
          <PnLChart title="Equity Curve" data={equityCurveData} />
        </ComponentErrorBoundary>
      </div>

      {/* Trade List */}
      <div className="rounded border border-[var(--color-border)] bg-[var(--color-bg-card)]">
        <div className="px-3 py-1.5 border-b border-[var(--color-border)]">
          <span className="text-sm font-medium">Trade List</span>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-xs">
            <thead>
              <tr className="text-[var(--color-text-secondary)] border-b border-[var(--color-border)]">
                <th scope="col" className="text-left px-3 py-2 font-medium">Time</th>
                <th scope="col" className="text-left px-3 py-2 font-medium">Symbol</th>
                <th scope="col" className="text-left px-3 py-2 font-medium">Side</th>
                <th scope="col" className="text-right px-3 py-2 font-medium">Entry</th>
                <th scope="col" className="text-right px-3 py-2 font-medium">Exit</th>
                <th scope="col" className="text-right px-3 py-2 font-medium">P&L</th>
              </tr>
            </thead>
            <tbody>
              {trades.length > 0 ? (
                trades.map((trade, i) => {
                  const sideStr = trade.side === 1 ? 'BUY' : trade.side === 2 ? 'SELL' : 'UNKNOWN';
                  const isBuy = trade.side === 1;
                  const entryTime = new Date(Number(trade.entryTimeUnixNanos) / 1_000_000).toISOString();
                  return (
                    <tr key={i} className="border-b border-[var(--color-border)] hover:bg-[var(--color-bg-primary)]">
                      <td className="px-3 py-1.5">{entryTime.slice(0, 19).replace('T', ' ')}</td>
                      <td className="px-3 py-1.5">{trade.symbol}</td>
                      <td className={`px-3 py-1.5 ${isBuy ? 'text-[var(--color-green)]' : 'text-[var(--color-red)]'}`}>
                        {sideStr}
                      </td>
                      <td className="px-3 py-1.5 text-right">{trade.entryPrice.toFixed(2)}</td>
                      <td className="px-3 py-1.5 text-right">{trade.exitPrice.toFixed(2)}</td>
                      <td className={`px-3 py-1.5 text-right ${trade.pnl >= 0 ? 'text-[var(--color-green)]' : 'text-[var(--color-red)]'}`}>
                        ${trade.pnl.toFixed(2)}
                      </td>
                    </tr>
                  );
                })
              ) : (
                <tr>
                  <td colSpan={6} className="text-center py-8 text-[var(--color-text-secondary)]">
                    Run a backtest to see results
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
