import { useState } from 'react';
import { ComponentErrorBoundary } from '../components/common/ComponentErrorBoundary';
import { useConfig, useUpdateConfig } from '../hooks/useApi';

type ConfigCategory = 'trading' | 'risk' | 'ml' | 'system';

interface ConfigFieldDef {
  key: string;
  value: string;
  description: string;
}

export function ConfigDashboard() {
  const [activeTab, setActiveTab] = useState<ConfigCategory>('trading');

  const config = useConfig();

  return (
    <div className="space-y-4">
      {config.isError && (
        <div role="alert" className="px-3 py-2 rounded border border-[var(--color-red)] bg-red-500/10 text-sm text-[var(--color-red)] flex items-center justify-between">
          <span>Failed to load configuration: {config.error.message}</span>
          <button onClick={() => config.refetch()} className="text-xs underline">Retry</button>
        </div>
      )}

      {/* Tabs */}
      <div role="tablist" className="flex gap-1 border-b border-[var(--color-border)] pb-0">
        {(['trading', 'risk', 'ml', 'system'] as const).map((tab) => (
          <button
            key={tab}
            role="tab"
            aria-selected={activeTab === tab}
            onClick={() => setActiveTab(tab)}
            className={`px-4 py-2 text-sm capitalize rounded-t transition-colors ${
              activeTab === tab
                ? 'bg-[var(--color-bg-card)] text-[var(--color-text-primary)] border border-[var(--color-border)] border-b-transparent -mb-px'
                : 'text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]'
            }`}
          >
            {tab}
          </button>
        ))}
      </div>

      {/* Config form */}
      <ComponentErrorBoundary name="Configuration Form">
        <div className="rounded border border-[var(--color-border)] bg-[var(--color-bg-card)]">
          <ConfigSection category={activeTab} settings={config.data?.settings} />
        </div>
      </ComponentErrorBoundary>

      {/* Audit Log */}
      <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">Change Audit Log</span>
        </div>
        <div className="p-4 text-sm text-[var(--color-text-secondary)] text-center">
          No recent configuration changes
        </div>
      </div>
    </div>
  );
}

function ConfigSection({
  category,
  settings,
}: {
  category: ConfigCategory;
  settings?: { key: string; value: string; category: string }[];
}) {
  const defaults: Record<ConfigCategory, ConfigFieldDef[]> = {
    trading: [
      { key: 'max_position_size', value: '1000', description: 'Maximum position size per symbol' },
      { key: 'max_order_value', value: '100000', description: 'Maximum order value in USD' },
      { key: 'default_slippage_bps', value: '5', description: 'Default slippage tolerance (bps)' },
      { key: 'order_timeout_ms', value: '5000', description: 'Order submission timeout' },
    ],
    risk: [
      { key: 'var_limit_pct', value: '2.0', description: 'Portfolio VaR limit (%)' },
      { key: 'max_drawdown_pct', value: '10.0', description: 'Maximum drawdown before halt (%)' },
      { key: 'position_limit_pct', value: '25.0', description: 'Max position as % of portfolio' },
      { key: 'kill_switch_loss', value: '50000', description: 'Kill switch loss threshold (USD)' },
    ],
    ml: [
      { key: 'ensemble_threshold', value: '0.6', description: 'Minimum ensemble confidence to trade' },
      { key: 'retrain_interval_hours', value: '24', description: 'Model retrain interval (hours)' },
      { key: 'prediction_horizon', value: '5', description: 'Prediction horizon (minutes)' },
      { key: 'regime_lookback', value: '100', description: 'Regime detection lookback (bars)' },
    ],
    system: [
      { key: 'log_level', value: 'info', description: 'Logging level (trace/debug/info/warn/error)' },
      { key: 'grpc_timeout_ms', value: '10000', description: 'gRPC client timeout' },
      { key: 'stream_heartbeat_interval', value: '30', description: 'Stream heartbeat interval (s)' },
      { key: 'metrics_push_interval', value: '5', description: 'Metrics push interval (s)' },
    ],
  };

  // Merge server values over defaults
  const fields = defaults[category].map((field) => {
    const serverSetting = settings?.find(
      (s) => s.key === field.key && s.category === category,
    );
    return {
      ...field,
      value: serverSetting?.value ?? field.value,
    };
  });

  const updateConfig = useUpdateConfig();

  return (
    <div className="divide-y divide-[var(--color-border)]">
      {fields.map((field) => (
        <div key={field.key} className="flex items-center gap-4 px-3 py-3">
          <div className="flex-1">
            <label htmlFor={`config-${field.key}`} className="text-sm font-mono">{field.key}</label>
            <div className="text-xs text-[var(--color-text-secondary)]">
              {field.description}
            </div>
          </div>
          <input
            id={`config-${field.key}`}
            type="text"
            defaultValue={field.value}
            className="w-32 px-2 py-1 text-sm text-right rounded border border-[var(--color-border)] bg-[var(--color-bg-primary)] text-[var(--color-text-primary)] outline-none focus:border-[var(--color-accent)]"
            onBlur={(e) => {
              if (e.target.value !== field.value) {
                updateConfig.mutate({
                  key: field.key,
                  value: e.target.value,
                  category,
                });
              }
            }}
          />
        </div>
      ))}
    </div>
  );
}
