import { useState } from 'react';
import {
  useTradingStatus,
  usePauseTradingEngine,
  useResumeTradingEngine,
  useUpdateTradingConfig,
  useTradingMetrics,
} from '../../api/tradingHooks';
import { Card, LoadingSpinner, StatusBadge } from '../../components/ui';

const RISK_TIERS = ['conservative', 'moderate', 'aggressive'];

function fmtUsd(v: number | null | undefined) {
  if (v == null) return '—';
  return `$${v.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}

function fmtPct(v: number | null | undefined) {
  if (v == null) return '—';
  return `${(v * 100).toFixed(2)}%`;
}

function cooldownRemaining(expires: string | null | undefined): string {
  if (!expires) return '';
  const ms = new Date(expires).getTime() - Date.now();
  if (ms <= 0) return 'expired';
  const mins = Math.ceil(ms / 60000);
  return mins >= 60 ? `${Math.floor(mins / 60)}h ${mins % 60}m` : `${mins}m`;
}

export function TradingOverview() {
  const { data: status, isLoading } = useTradingStatus();
  const { data: metrics } = useTradingMetrics();
  const pause = usePauseTradingEngine();
  const resume = useResumeTradingEngine();
  const updateConfig = useUpdateTradingConfig();
  const [selectedTier, setSelectedTier] = useState<string | null>(null);
  const [maxPositions, setMaxPositions] = useState<number | null>(null);
  const [positionCap, setPositionCap] = useState<number | null>(null);

  if (isLoading) return <LoadingSpinner />;
  if (!status) return <p className="text-gray-500">No trading status available</p>;

  const effectiveTier = selectedTier ?? status.risk_tier;

  function handleTierChange(tier: string) {
    setSelectedTier(tier);
    updateConfig.mutate({ risk_tier: tier });
  }

  return (
    <div className="space-y-4">
      {/* Controls */}
      <Card>
        <div className="flex items-center justify-between">
          <h2 className="text-sm font-medium text-gray-400">Engine Controls</h2>
          <div className="flex items-center gap-2">
            {status.paused ? (
              <button
                onClick={() => resume.mutate()}
                disabled={resume.isPending}
                className="rounded-md bg-green-700 px-3 py-1.5 text-xs font-medium text-white hover:bg-green-600 disabled:opacity-50"
              >
                Resume
              </button>
            ) : (
              <button
                onClick={() => pause.mutate()}
                disabled={pause.isPending}
                className="rounded-md bg-yellow-700 px-3 py-1.5 text-xs font-medium text-white hover:bg-yellow-600 disabled:opacity-50"
              >
                Pause
              </button>
            )}
          </div>
        </div>
        <div className="mt-3 flex items-center gap-4">
          <StatusBadge status={status.paused ? 'paused' : status.enabled ? 'active' : 'disabled'} />
          <span className="text-xs text-gray-500">
            {status.open_position_count} open positions
          </span>
          {status.last_decision_at && (
            <span className="text-xs text-gray-500">
              Last decision: {new Date(status.last_decision_at).toLocaleString()}
            </span>
          )}
        </div>
      </Card>

      {/* Risk Tier & Circuit Breaker */}
      <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
        <Card>
          <h2 className="mb-3 text-sm font-medium text-gray-400">Risk Tier</h2>
          <select
            value={effectiveTier}
            onChange={(e) => handleTierChange(e.target.value)}
            className="rounded-md border border-surface-700 bg-surface-950 px-3 py-1.5 text-sm text-gray-200 focus:border-brand-500 focus:outline-none"
            aria-label="Risk tier selector"
          >
            {RISK_TIERS.map((t) => (
              <option key={t} value={t}>
                {t.charAt(0).toUpperCase() + t.slice(1)}
              </option>
            ))}
          </select>
        </Card>

        <Card>
          <h2 className="mb-3 text-sm font-medium text-gray-400">Circuit Breaker</h2>
          <div className="flex items-center gap-3">
            <StatusBadge status={status.circuit_breaker_active ? 'active' : 'inactive'} />
            {status.circuit_breaker_active && (
              <div className="text-xs text-gray-400">
                {status.circuit_breaker_trigger_type && (
                  <span>Trigger: {status.circuit_breaker_trigger_type}</span>
                )}
                {status.circuit_breaker_cooldown_expires && (
                  <span className="ml-2">
                    Cooldown: {cooldownRemaining(status.circuit_breaker_cooldown_expires)}
                  </span>
                )}
              </div>
            )}
          </div>
        </Card>
      </div>

      {/* Pool Balances & Portfolio Heat */}
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
        <StatCard label="Active Pool" value={fmtUsd(status.active_pool)} />
        <StatCard label="Reserve Pool" value={fmtUsd(status.reserve_pool)} />
        <StatCard label="Portfolio Value" value={fmtUsd(status.portfolio_value)} />
        <StatCard label="Portfolio Heat" value={fmtPct(status.portfolio_heat)} />
      </div>

      {/* Position Limits */}
      <Card>
        <h2 className="mb-3 text-sm font-medium text-gray-400">Position Limits</h2>
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div>
            <label htmlFor="max-positions" className="block text-xs text-gray-500 mb-1">
              Max Open Positions
            </label>
            <div className="flex items-center gap-2">
              <input
                id="max-positions"
                type="number"
                min={1}
                max={50}
                value={maxPositions ?? status.max_open_positions ?? 10}
                onChange={(e) => setMaxPositions(Number(e.target.value))}
                className="w-20 rounded-md border border-surface-700 bg-surface-950 px-2 py-1.5 text-sm text-gray-200 focus:border-brand-500 focus:outline-none"
              />
              <button
                onClick={() => {
                  const val = maxPositions ?? status.max_open_positions ?? 10;
                  updateConfig.mutate({ max_open_positions: val });
                }}
                disabled={updateConfig.isPending}
                className="rounded-md bg-brand-700 px-3 py-1.5 text-xs font-medium text-white hover:bg-brand-600 disabled:opacity-50"
              >
                Apply
              </button>
              <span className="text-xs text-gray-500">
                Current: {status.open_position_count ?? 0} / {status.max_open_positions ?? 10}
              </span>
            </div>
          </div>
          <div>
            <label htmlFor="position-cap" className="block text-xs text-gray-500 mb-1">
              Absolute Position Cap ($)
            </label>
            <div className="flex items-center gap-2">
              <input
                id="position-cap"
                type="number"
                min={10}
                step={10}
                value={positionCap ?? status.absolute_position_cap ?? 50}
                onChange={(e) => setPositionCap(Number(e.target.value))}
                className="w-24 rounded-md border border-surface-700 bg-surface-950 px-2 py-1.5 text-sm text-gray-200 focus:border-brand-500 focus:outline-none"
              />
              <button
                onClick={() => {
                  const val = positionCap ?? status.absolute_position_cap ?? 50;
                  updateConfig.mutate({ absolute_position_cap: val });
                }}
                disabled={updateConfig.isPending}
                className="rounded-md bg-brand-700 px-3 py-1.5 text-xs font-medium text-white hover:bg-brand-600 disabled:opacity-50"
              >
                Apply
              </button>
            </div>
          </div>
        </div>
      </Card>

      {/* Portfolio Heat Gauge */}
      <Card>
        <h2 className="mb-2 text-sm font-medium text-gray-400">Portfolio Heat</h2>
        <div className="h-3 w-full rounded-full bg-surface-700">
          <div
            className={`h-full rounded-full transition-all ${
              (status.portfolio_heat ?? 0) > 0.8
                ? 'bg-red-500'
                : (status.portfolio_heat ?? 0) > 0.5
                  ? 'bg-yellow-500'
                  : 'bg-green-500'
            }`}
            style={{ width: `${Math.min(100, (status.portfolio_heat ?? 0) * 100)}%` }}
          />
        </div>
        <div className="mt-1 flex justify-between text-xs text-gray-500">
          <span>0%</span>
          <span>{((status.portfolio_heat ?? 0) * 100).toFixed(1)}%</span>
          <span>100%</span>
        </div>
      </Card>

      {/* 24h P&L Summary */}
      {metrics && (
        <Card>
          <h2 className="mb-3 text-sm font-medium text-gray-400">Last 24h P&amp;L Summary</h2>
          <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
            <MiniStat label="Daily P&L" value={fmtUsd(metrics.daily_pnl)} color={pnlColor(metrics.daily_pnl)} />
            <MiniStat label="Unrealized" value={fmtUsd(metrics.unrealized_pnl)} color={pnlColor(metrics.unrealized_pnl)} />
            <MiniStat label="Win Rate" value={fmtPct(metrics.win_rate)} />
            <MiniStat label="Profit Factor" value={metrics.profit_factor?.toFixed(2) ?? '—'} />
          </div>
        </Card>
      )}
    </div>
  );
}

function pnlColor(v: number | null | undefined) {
  if (v == null) return 'text-gray-300';
  return v >= 0 ? 'text-green-400' : 'text-red-400';
}

function StatCard({ label, value }: { label: string; value: string }) {
  return (
    <Card className="text-center">
      <div className="text-lg font-bold text-gray-100">{value}</div>
      <div className="text-xs text-gray-500">{label}</div>
    </Card>
  );
}

function MiniStat({ label, value, color = 'text-gray-100' }: { label: string; value: string; color?: string }) {
  return (
    <div>
      <div className={`text-sm font-semibold ${color}`}>{value}</div>
      <div className="text-xs text-gray-500">{label}</div>
    </div>
  );
}
