/**
 * AgentSettingsPage
 * Full page for configuring the LLM trading agent
 * OQI-007: LLM Strategy Agent - Settings Page
 */

import React, { useState, useEffect, useCallback } from 'react';
import { Link } from 'react-router-dom';
import {
  ArrowLeftIcon,
  Cog6ToothIcon,
  CircleStackIcon,
  WrenchScrewdriverIcon,
  BoltIcon,
  BellIcon,
  ShieldCheckIcon,
  ArrowPathIcon,
  CheckIcon,
  ExclamationCircleIcon,
} from '@heroicons/react/24/outline';

// Components
import MemoryManagerPanel, { MemoryItem, MemoryStats, MemoryCategory } from '../components/MemoryManagerPanel';
import ToolsConfigPanel, { AgentTool } from '../components/ToolsConfigPanel';
import AgentModeSelector, { AgentModeConfig, AgentMode, TriggerCondition, ActivitySchedule } from '../components/AgentModeSelector';

// ============================================================================
// Types
// ============================================================================

type SettingsTab = 'mode' | 'memory' | 'tools' | 'notifications' | 'limits';

interface NotificationSettings {
  emailNotifications: boolean;
  pushNotifications: boolean;
  signalAlerts: boolean;
  riskAlerts: boolean;
  dailyDigest: boolean;
  weeklyReport: boolean;
}

interface OperationLimits {
  maxDailyTrades: number;
  maxPositionSize: number;
  maxDailyLoss: number;
  maxDrawdown: number;
  pauseOnLossStreak: number;
}

// ============================================================================
// Constants
// ============================================================================

const TABS: { id: SettingsTab; label: string; icon: React.ElementType }[] = [
  { id: 'mode', label: 'Modo', icon: BoltIcon },
  { id: 'memory', label: 'Memoria', icon: CircleStackIcon },
  { id: 'tools', label: 'Herramientas', icon: WrenchScrewdriverIcon },
  { id: 'notifications', label: 'Notificaciones', icon: BellIcon },
  { id: 'limits', label: 'Limites', icon: ShieldCheckIcon },
];

// Mock data - would come from API
const MOCK_MEMORIES: MemoryItem[] = [
  {
    id: '1',
    category: 'preferences',
    key: 'risk_tolerance',
    value: 'Prefiero operaciones conservadoras con stop loss ajustado. Maximo 1% de riesgo por operacion.',
    createdAt: '2026-02-01T10:00:00Z',
    updatedAt: '2026-02-03T15:30:00Z',
    isPinned: true,
  },
  {
    id: '2',
    category: 'strategies',
    key: 'preferred_setup',
    value: 'Setup favorito: Ruptura de estructura en H4 con confirmacion en M15. Buscar FVG y OB.',
    createdAt: '2026-02-02T09:00:00Z',
    updatedAt: '2026-02-02T09:00:00Z',
  },
  {
    id: '3',
    category: 'history',
    key: 'last_analysis',
    value: 'Ultimo analisis de XAUUSD mostro fase de distribucion. Se identifico zona de demanda en 2040.',
    createdAt: '2026-02-03T08:00:00Z',
    updatedAt: '2026-02-03T08:00:00Z',
  },
];

const MOCK_STATS: MemoryStats = {
  totalItems: 15,
  totalTokens: 4500,
  maxTokens: 8000,
  byCategory: { preferences: 5, strategies: 4, history: 4, custom: 2 },
};

const MOCK_TOOLS: AgentTool[] = [
  {
    id: 'market_analysis',
    name: 'Analisis de Mercado',
    description: 'Analiza datos de mercado en tiempo real incluyendo precio, volumen y estructura.',
    category: 'analysis',
    enabled: true,
    isCore: true,
    parameters: [],
    parameterValues: {},
    usageCount: 156,
    lastUsed: '2026-02-04T10:30:00Z',
  },
  {
    id: 'order_execution',
    name: 'Ejecucion de Ordenes',
    description: 'Permite al agente sugerir y preparar ordenes de trading.',
    category: 'trading',
    enabled: true,
    parameters: [
      { name: 'require_confirmation', type: 'boolean', label: 'Requerir confirmacion', default: true },
      { name: 'default_risk', type: 'number', label: 'Riesgo por defecto (%)', default: 1, min: 0.1, max: 5 },
    ],
    parameterValues: { require_confirmation: true, default_risk: 1 },
    requiredPermissions: ['trading:execute'],
    usageCount: 42,
    lastUsed: '2026-02-03T18:00:00Z',
  },
  {
    id: 'risk_calculator',
    name: 'Calculadora de Riesgo',
    description: 'Calcula tamano de posicion y riesgo basado en tu configuracion.',
    category: 'risk',
    enabled: true,
    isCore: true,
    parameters: [],
    parameterValues: {},
    usageCount: 89,
    lastUsed: '2026-02-04T09:15:00Z',
  },
  {
    id: 'news_analyzer',
    name: 'Analizador de Noticias',
    description: 'Analiza noticias y eventos del mercado para identificar impacto potencial.',
    category: 'data',
    enabled: false,
    parameters: [
      { name: 'sources', type: 'select', label: 'Fuentes', default: 'all', options: [
        { value: 'all', label: 'Todas' },
        { value: 'forex', label: 'Solo Forex' },
        { value: 'crypto', label: 'Solo Crypto' },
      ]},
    ],
    parameterValues: { sources: 'all' },
    usageCount: 23,
    lastUsed: '2026-02-01T12:00:00Z',
  },
  {
    id: 'backtester',
    name: 'Backtester',
    description: 'Ejecuta backtests sobre estrategias y configuraciones.',
    category: 'analysis',
    enabled: true,
    parameters: [
      { name: 'default_period', type: 'select', label: 'Periodo por defecto', default: '90', options: [
        { value: '30', label: '30 dias' },
        { value: '90', label: '90 dias' },
        { value: '180', label: '180 dias' },
        { value: '365', label: '1 ano' },
      ]},
    ],
    parameterValues: { default_period: '90' },
    usageCount: 12,
    lastUsed: '2026-02-02T14:00:00Z',
  },
];

const MOCK_MODE_CONFIG: AgentModeConfig = {
  mode: 'reactive',
  triggers: [
    { id: '1', type: 'signal_generated', name: 'Senal de alta confianza', enabled: true, config: { minConfidence: 0.85 } },
    { id: '2', type: 'risk_threshold', name: 'Alerta de drawdown', enabled: true, config: { threshold: 5 } },
    { id: '3', type: 'price_alert', name: 'Precio objetivo alcanzado', enabled: false, config: {} },
  ],
  schedules: TABS.map((_, i) => ({
    id: String(i),
    dayOfWeek: i,
    startTime: '09:00',
    endTime: '17:00',
    enabled: i >= 1 && i <= 5,
  })),
  notifyOnAction: true,
  requireConfirmation: true,
  maxActionsPerHour: 5,
};

// ============================================================================
// Main Component
// ============================================================================

const AgentSettingsPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState<SettingsTab>('mode');
  const [isLoading, setIsLoading] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [saveSuccess, setSaveSuccess] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // State
  const [memories, setMemories] = useState<MemoryItem[]>(MOCK_MEMORIES);
  const [memoryStats, setMemoryStats] = useState<MemoryStats>(MOCK_STATS);
  const [tools, setTools] = useState<AgentTool[]>(MOCK_TOOLS);
  const [modeConfig, setModeConfig] = useState<AgentModeConfig>(MOCK_MODE_CONFIG);
  const [notifications, setNotifications] = useState<NotificationSettings>({
    emailNotifications: true,
    pushNotifications: true,
    signalAlerts: true,
    riskAlerts: true,
    dailyDigest: false,
    weeklyReport: true,
  });
  const [limits, setLimits] = useState<OperationLimits>({
    maxDailyTrades: 10,
    maxPositionSize: 2,
    maxDailyLoss: 3,
    maxDrawdown: 10,
    pauseOnLossStreak: 3,
  });

  // Handlers - Memory
  const handleAddMemory = useCallback(async (memory: Omit<MemoryItem, 'id' | 'createdAt' | 'updatedAt'>) => {
    const newMemory: MemoryItem = {
      ...memory,
      id: Date.now().toString(),
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    setMemories((prev) => [newMemory, ...prev]);
    setMemoryStats((prev) => ({
      ...prev,
      totalItems: prev.totalItems + 1,
      byCategory: { ...prev.byCategory, [memory.category]: (prev.byCategory[memory.category] || 0) + 1 },
    }));
  }, []);

  const handleUpdateMemory = useCallback(async (id: string, updates: Partial<MemoryItem>) => {
    setMemories((prev) => prev.map((m) =>
      m.id === id ? { ...m, ...updates, updatedAt: new Date().toISOString() } : m
    ));
  }, []);

  const handleDeleteMemory = useCallback(async (id: string) => {
    const memory = memories.find((m) => m.id === id);
    if (memory) {
      setMemories((prev) => prev.filter((m) => m.id !== id));
      setMemoryStats((prev) => ({
        ...prev,
        totalItems: prev.totalItems - 1,
        byCategory: { ...prev.byCategory, [memory.category]: prev.byCategory[memory.category] - 1 },
      }));
    }
  }, [memories]);

  // Handlers - Tools
  const handleToggleTool = useCallback((toolId: string, enabled: boolean) => {
    setTools((prev) => prev.map((t) => t.id === toolId ? { ...t, enabled } : t));
  }, []);

  const handleUpdateToolParams = useCallback((toolId: string, params: Record<string, string | number | boolean>) => {
    setTools((prev) => prev.map((t) => t.id === toolId ? { ...t, parameterValues: params } : t));
  }, []);

  // Handlers - Mode
  const handleModeChange = useCallback((mode: AgentMode) => {
    setModeConfig((prev) => ({ ...prev, mode }));
  }, []);

  const handleUpdateTrigger = useCallback((triggerId: string, updates: Partial<TriggerCondition>) => {
    setModeConfig((prev) => ({
      ...prev,
      triggers: prev.triggers.map((t) => t.id === triggerId ? { ...t, ...updates } : t),
    }));
  }, []);

  const handleUpdateSchedule = useCallback((scheduleId: string, updates: Partial<ActivitySchedule>) => {
    setModeConfig((prev) => ({
      ...prev,
      schedules: prev.schedules.map((s) => s.id === scheduleId ? { ...s, ...updates } : s),
    }));
  }, []);

  const handleUpdateModeConfig = useCallback((updates: Partial<AgentModeConfig>) => {
    setModeConfig((prev) => ({ ...prev, ...updates }));
  }, []);

  // Save all settings
  const handleSaveAll = useCallback(async () => {
    setIsSaving(true);
    setError(null);
    try {
      // Simulate API call
      await new Promise((resolve) => setTimeout(resolve, 1000));
      setSaveSuccess(true);
      setTimeout(() => setSaveSuccess(false), 3000);
    } catch (err) {
      setError('Error al guardar la configuracion');
    } finally {
      setIsSaving(false);
    }
  }, []);

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900">
      {/* Header */}
      <div className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-16">
            <div className="flex items-center gap-4">
              <Link
                to="/assistant"
                className="p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
              >
                <ArrowLeftIcon className="w-5 h-5" />
              </Link>
              <div className="flex items-center gap-3">
                <div className="p-2 bg-gradient-to-r from-cyan-500 to-blue-500 rounded-lg">
                  <Cog6ToothIcon className="w-5 h-5 text-white" />
                </div>
                <div>
                  <h1 className="font-bold text-gray-900 dark:text-white">Configuracion del Agente</h1>
                  <p className="text-xs text-gray-500">Personaliza tu asistente de trading</p>
                </div>
              </div>
            </div>
            <div className="flex items-center gap-3">
              {saveSuccess && (
                <div className="flex items-center gap-2 text-sm text-emerald-600 dark:text-emerald-400">
                  <CheckIcon className="w-4 h-4" />
                  Guardado
                </div>
              )}
              {error && (
                <div className="flex items-center gap-2 text-sm text-red-600 dark:text-red-400">
                  <ExclamationCircleIcon className="w-4 h-4" />
                  {error}
                </div>
              )}
              <button
                onClick={handleSaveAll}
                disabled={isSaving}
                className="flex items-center gap-2 px-4 py-2 bg-primary-500 text-white rounded-lg hover:bg-primary-600 disabled:opacity-50 transition-colors"
              >
                {isSaving ? (
                  <ArrowPathIcon className="w-4 h-4 animate-spin" />
                ) : (
                  <CheckIcon className="w-4 h-4" />
                )}
                Guardar Cambios
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="flex gap-8">
          {/* Sidebar Tabs */}
          <div className="w-56 flex-shrink-0">
            <nav className="space-y-1">
              {TABS.map((tab) => {
                const Icon = tab.icon;
                return (
                  <button
                    key={tab.id}
                    onClick={() => setActiveTab(tab.id)}
                    className={`w-full flex items-center gap-3 px-4 py-3 rounded-lg text-left transition-colors ${
                      activeTab === tab.id
                        ? 'bg-primary-50 dark:bg-primary-900/20 text-primary-600 dark:text-primary-400 font-medium'
                        : 'text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800'
                    }`}
                  >
                    <Icon className="w-5 h-5" />
                    {tab.label}
                  </button>
                );
              })}
            </nav>
          </div>

          {/* Content */}
          <div className="flex-1 min-w-0">
            {activeTab === 'mode' && (
              <AgentModeSelector
                config={modeConfig}
                onModeChange={handleModeChange}
                onUpdateTrigger={handleUpdateTrigger}
                onUpdateSchedule={handleUpdateSchedule}
                onUpdateConfig={handleUpdateModeConfig}
              />
            )}

            {activeTab === 'memory' && (
              <MemoryManagerPanel
                memories={memories}
                stats={memoryStats}
                onAddMemory={handleAddMemory}
                onUpdateMemory={handleUpdateMemory}
                onDeleteMemory={handleDeleteMemory}
                isLoading={isLoading}
              />
            )}

            {activeTab === 'tools' && (
              <ToolsConfigPanel
                tools={tools}
                onToggleTool={handleToggleTool}
                onUpdateToolParams={handleUpdateToolParams}
                isLoading={isLoading}
              />
            )}

            {activeTab === 'notifications' && (
              <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
                <div className="flex items-center gap-2 mb-6">
                  <BellIcon className="w-5 h-5 text-primary-500" />
                  <h3 className="font-semibold text-gray-900 dark:text-white">Notificaciones</h3>
                </div>
                <div className="space-y-4">
                  {Object.entries(notifications).map(([key, value]) => (
                    <div key={key} className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                      <div>
                        <p className="text-sm font-medium text-gray-900 dark:text-white">
                          {key.replace(/([A-Z])/g, ' $1').replace(/^./, (s) => s.toUpperCase())}
                        </p>
                      </div>
                      <button
                        onClick={() => setNotifications((prev) => ({ ...prev, [key]: !value }))}
                        className={`relative w-11 h-6 rounded-full transition-colors ${
                          value ? 'bg-primary-500' : 'bg-gray-300 dark:bg-gray-600'
                        }`}
                      >
                        <div className={`absolute top-1 w-4 h-4 bg-white rounded-full transition-transform ${
                          value ? 'translate-x-6' : 'translate-x-1'
                        }`} />
                      </button>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {activeTab === 'limits' && (
              <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
                <div className="flex items-center gap-2 mb-6">
                  <ShieldCheckIcon className="w-5 h-5 text-primary-500" />
                  <h3 className="font-semibold text-gray-900 dark:text-white">Limites de Operacion</h3>
                </div>
                <div className="space-y-6">
                  {[
                    { key: 'maxDailyTrades', label: 'Max operaciones por dia', min: 1, max: 50, unit: '' },
                    { key: 'maxPositionSize', label: 'Max tamano posicion', min: 0.5, max: 10, unit: '%' },
                    { key: 'maxDailyLoss', label: 'Max perdida diaria', min: 1, max: 10, unit: '%' },
                    { key: 'maxDrawdown', label: 'Max drawdown total', min: 5, max: 30, unit: '%' },
                    { key: 'pauseOnLossStreak', label: 'Pausar tras perdidas consecutivas', min: 2, max: 10, unit: '' },
                  ].map((item) => (
                    <div key={item.key}>
                      <div className="flex items-center justify-between mb-2">
                        <p className="text-sm font-medium text-gray-700 dark:text-gray-300">{item.label}</p>
                        <span className="text-sm text-primary-500 font-medium">
                          {limits[item.key as keyof OperationLimits]}{item.unit}
                        </span>
                      </div>
                      <input
                        type="range"
                        min={item.min}
                        max={item.max}
                        step={item.key === 'maxPositionSize' ? 0.5 : 1}
                        value={limits[item.key as keyof OperationLimits]}
                        onChange={(e) => setLimits((prev) => ({
                          ...prev,
                          [item.key]: parseFloat(e.target.value),
                        }))}
                        className="w-full"
                      />
                      <div className="flex justify-between text-xs text-gray-400 mt-1">
                        <span>{item.min}{item.unit}</span>
                        <span>{item.max}{item.unit}</span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default AgentSettingsPage;
