/**
 * AgentModeSelector Component
 * Toggle between proactive and reactive agent modes with configuration
 * OQI-007: LLM Strategy Agent - Agent Mode Selection UI
 */

import React, { useState, useCallback } from 'react';
import {
  BoltIcon,
  HandRaisedIcon,
  ClockIcon,
  BellIcon,
  ChartBarIcon,
  ExclamationTriangleIcon,
  InformationCircleIcon,
  Cog6ToothIcon,
  ChevronDownIcon,
  ChevronUpIcon,
  CheckIcon,
  PlusIcon,
  XMarkIcon,
} from '@heroicons/react/24/outline';
import { BoltIcon as BoltSolidIcon, HandRaisedIcon as HandRaisedSolidIcon } from '@heroicons/react/24/solid';

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

export type AgentMode = 'proactive' | 'reactive';

export interface TriggerCondition {
  id: string;
  type: 'price_alert' | 'signal_generated' | 'risk_threshold' | 'market_event' | 'schedule';
  name: string;
  enabled: boolean;
  config: Record<string, unknown>;
}

export interface ActivitySchedule {
  id: string;
  dayOfWeek: number; // 0-6 (Sunday-Saturday)
  startTime: string; // HH:MM
  endTime: string; // HH:MM
  enabled: boolean;
}

export interface AgentModeConfig {
  mode: AgentMode;
  triggers: TriggerCondition[];
  schedules: ActivitySchedule[];
  notifyOnAction: boolean;
  requireConfirmation: boolean;
  maxActionsPerHour: number;
}

interface AgentModeSelectorProps {
  config: AgentModeConfig;
  onModeChange: (mode: AgentMode) => void;
  onUpdateTrigger: (triggerId: string, updates: Partial<TriggerCondition>) => void;
  onAddTrigger?: () => void;
  onRemoveTrigger?: (triggerId: string) => void;
  onUpdateSchedule: (scheduleId: string, updates: Partial<ActivitySchedule>) => void;
  onUpdateConfig: (updates: Partial<AgentModeConfig>) => void;
  isLoading?: boolean;
}

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

const TRIGGER_TYPES: Record<string, { label: string; icon: React.ElementType; description: string }> = {
  price_alert: {
    label: 'Alerta de Precio',
    icon: ChartBarIcon,
    description: 'Cuando un precio alcanza cierto nivel',
  },
  signal_generated: {
    label: 'Senal Generada',
    icon: BoltIcon,
    description: 'Cuando se genera una senal de trading',
  },
  risk_threshold: {
    label: 'Umbral de Riesgo',
    icon: ExclamationTriangleIcon,
    description: 'Cuando se supera un nivel de riesgo',
  },
  market_event: {
    label: 'Evento de Mercado',
    icon: BellIcon,
    description: 'Noticias o eventos importantes',
  },
  schedule: {
    label: 'Programado',
    icon: ClockIcon,
    description: 'En horarios especificos',
  },
};

const DAYS_OF_WEEK = [
  { value: 0, label: 'Dom' },
  { value: 1, label: 'Lun' },
  { value: 2, label: 'Mar' },
  { value: 3, label: 'Mie' },
  { value: 4, label: 'Jue' },
  { value: 5, label: 'Vie' },
  { value: 6, label: 'Sab' },
];

// ============================================================================
// Sub-Components
// ============================================================================

interface ModeCardProps {
  mode: AgentMode;
  isSelected: boolean;
  onSelect: () => void;
}

const ModeCard: React.FC<ModeCardProps> = ({ mode, isSelected, onSelect }) => {
  const isProactive = mode === 'proactive';
  const Icon = isProactive ? (isSelected ? BoltSolidIcon : BoltIcon) : (isSelected ? HandRaisedSolidIcon : HandRaisedIcon);

  return (
    <button
      onClick={onSelect}
      className={`flex-1 p-4 rounded-xl border-2 transition-all ${
        isSelected
          ? isProactive
            ? 'border-amber-500 bg-amber-50 dark:bg-amber-900/20'
            : 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
          : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
      }`}
    >
      <div className="flex flex-col items-center text-center">
        <div className={`p-3 rounded-full mb-3 ${
          isSelected
            ? isProactive
              ? 'bg-amber-500 text-white'
              : 'bg-blue-500 text-white'
            : 'bg-gray-100 dark:bg-gray-700 text-gray-500'
        }`}>
          <Icon className="w-6 h-6" />
        </div>
        <h4 className={`font-semibold mb-1 ${
          isSelected
            ? isProactive
              ? 'text-amber-700 dark:text-amber-300'
              : 'text-blue-700 dark:text-blue-300'
            : 'text-gray-900 dark:text-white'
        }`}>
          {isProactive ? 'Proactivo' : 'Reactivo'}
        </h4>
        <p className="text-xs text-gray-500">
          {isProactive
            ? 'El agente toma acciones automaticamente'
            : 'El agente solo responde a tus preguntas'}
        </p>
      </div>
    </button>
  );
};

interface TriggerItemProps {
  trigger: TriggerCondition;
  onToggle: (enabled: boolean) => void;
  onRemove?: () => void;
}

const TriggerItem: React.FC<TriggerItemProps> = ({ trigger, onToggle, onRemove }) => {
  const typeInfo = TRIGGER_TYPES[trigger.type];
  const Icon = typeInfo?.icon || BellIcon;

  return (
    <div className={`flex items-center gap-3 p-3 rounded-lg border transition-colors ${
      trigger.enabled
        ? 'border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800'
        : 'border-gray-100 dark:border-gray-800 bg-gray-50 dark:bg-gray-900 opacity-75'
    }`}>
      <div className={`p-2 rounded-lg ${
        trigger.enabled ? 'bg-amber-100 dark:bg-amber-900/30 text-amber-600 dark:text-amber-400' : 'bg-gray-100 dark:bg-gray-700 text-gray-400'
      }`}>
        <Icon className="w-4 h-4" />
      </div>
      <div className="flex-1 min-w-0">
        <p className="text-sm font-medium text-gray-900 dark:text-white">{trigger.name}</p>
        <p className="text-xs text-gray-500">{typeInfo?.description}</p>
      </div>
      <div className="flex items-center gap-2">
        {onRemove && (
          <button
            onClick={onRemove}
            className="p-1.5 text-gray-400 hover:text-red-500 rounded-lg"
          >
            <XMarkIcon className="w-4 h-4" />
          </button>
        )}
        <button
          onClick={() => onToggle(!trigger.enabled)}
          className={`relative w-10 h-6 rounded-full transition-colors ${
            trigger.enabled ? 'bg-amber-500' : 'bg-gray-300 dark:bg-gray-600'
          }`}
        >
          <div className={`absolute top-1 w-4 h-4 bg-white rounded-full transition-transform ${
            trigger.enabled ? 'translate-x-5' : 'translate-x-1'
          }`} />
        </button>
      </div>
    </div>
  );
};

interface ScheduleEditorProps {
  schedules: ActivitySchedule[];
  onUpdate: (scheduleId: string, updates: Partial<ActivitySchedule>) => void;
}

const ScheduleEditor: React.FC<ScheduleEditorProps> = ({ schedules, onUpdate }) => {
  return (
    <div className="space-y-3">
      <p className="text-sm font-medium text-gray-700 dark:text-gray-300">Horarios de Actividad</p>
      <div className="grid grid-cols-7 gap-1.5">
        {DAYS_OF_WEEK.map((day) => {
          const schedule = schedules.find((s) => s.dayOfWeek === day.value);
          return (
            <button
              key={day.value}
              onClick={() => {
                if (schedule) {
                  onUpdate(schedule.id, { enabled: !schedule.enabled });
                }
              }}
              className={`p-2 rounded-lg text-center transition-colors ${
                schedule?.enabled
                  ? 'bg-amber-500 text-white'
                  : 'bg-gray-100 dark:bg-gray-700 text-gray-500 hover:bg-gray-200 dark:hover:bg-gray-600'
              }`}
            >
              <span className="text-xs font-medium">{day.label}</span>
            </button>
          );
        })}
      </div>
      {schedules.filter((s) => s.enabled).length > 0 && (
        <div className="space-y-2">
          {schedules.filter((s) => s.enabled).map((schedule) => (
            <div key={schedule.id} className="flex items-center gap-3 p-2 bg-gray-50 dark:bg-gray-800 rounded-lg">
              <span className="text-xs text-gray-500 w-12">
                {DAYS_OF_WEEK.find((d) => d.value === schedule.dayOfWeek)?.label}
              </span>
              <input
                type="time"
                value={schedule.startTime}
                onChange={(e) => onUpdate(schedule.id, { startTime: e.target.value })}
                className="px-2 py-1 text-xs bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded"
              />
              <span className="text-xs text-gray-400">a</span>
              <input
                type="time"
                value={schedule.endTime}
                onChange={(e) => onUpdate(schedule.id, { endTime: e.target.value })}
                className="px-2 py-1 text-xs bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded"
              />
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

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

export const AgentModeSelector: React.FC<AgentModeSelectorProps> = ({
  config,
  onModeChange,
  onUpdateTrigger,
  onAddTrigger,
  onRemoveTrigger,
  onUpdateSchedule,
  onUpdateConfig,
  isLoading = false,
}) => {
  const [showAdvanced, setShowAdvanced] = useState(false);

  const handleModeChange = useCallback((mode: AgentMode) => {
    onModeChange(mode);
  }, [onModeChange]);

  return (
    <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
      {/* Header */}
      <div className="p-4 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center gap-2 mb-1">
          <BoltIcon className="w-5 h-5 text-primary-500" />
          <h3 className="font-semibold text-gray-900 dark:text-white">Modo del Agente</h3>
        </div>
        <p className="text-sm text-gray-500">
          Configura como interactua el agente contigo
        </p>
      </div>

      {/* Mode Selection */}
      <div className="p-4 border-b border-gray-200 dark:border-gray-700">
        <div className="flex gap-4">
          <ModeCard
            mode="reactive"
            isSelected={config.mode === 'reactive'}
            onSelect={() => handleModeChange('reactive')}
          />
          <ModeCard
            mode="proactive"
            isSelected={config.mode === 'proactive'}
            onSelect={() => handleModeChange('proactive')}
          />
        </div>
      </div>

      {/* Mode Description */}
      <div className="p-4 border-b border-gray-200 dark:border-gray-700">
        <div className={`p-4 rounded-lg ${
          config.mode === 'proactive'
            ? 'bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800'
            : 'bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800'
        }`}>
          <div className="flex items-start gap-3">
            <InformationCircleIcon className={`w-5 h-5 flex-shrink-0 ${
              config.mode === 'proactive' ? 'text-amber-500' : 'text-blue-500'
            }`} />
            <div>
              <h4 className={`font-medium text-sm ${
                config.mode === 'proactive' ? 'text-amber-800 dark:text-amber-200' : 'text-blue-800 dark:text-blue-200'
              }`}>
                Modo {config.mode === 'proactive' ? 'Proactivo' : 'Reactivo'} Activado
              </h4>
              <p className={`text-sm mt-1 ${
                config.mode === 'proactive' ? 'text-amber-700 dark:text-amber-300' : 'text-blue-700 dark:text-blue-300'
              }`}>
                {config.mode === 'proactive'
                  ? 'El agente te notificara sobre oportunidades, riesgos y eventos relevantes. Puede sugerir acciones automaticamente basado en los triggers configurados.'
                  : 'El agente solo respondera cuando le hagas preguntas. No enviara notificaciones ni tomara acciones por su cuenta.'}
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Proactive Mode Configuration */}
      {config.mode === 'proactive' && (
        <>
          {/* Triggers */}
          <div className="p-4 border-b border-gray-200 dark:border-gray-700">
            <div className="flex items-center justify-between mb-3">
              <h4 className="font-medium text-gray-900 dark:text-white">Triggers de Activacion</h4>
              {onAddTrigger && (
                <button
                  onClick={onAddTrigger}
                  className="flex items-center gap-1 text-xs text-primary-500 hover:text-primary-600"
                >
                  <PlusIcon className="w-4 h-4" />
                  Agregar
                </button>
              )}
            </div>
            <div className="space-y-2">
              {config.triggers.map((trigger) => (
                <TriggerItem
                  key={trigger.id}
                  trigger={trigger}
                  onToggle={(enabled) => onUpdateTrigger(trigger.id, { enabled })}
                  onRemove={onRemoveTrigger ? () => onRemoveTrigger(trigger.id) : undefined}
                />
              ))}
            </div>
          </div>

          {/* Schedule */}
          <div className="p-4 border-b border-gray-200 dark:border-gray-700">
            <ScheduleEditor
              schedules={config.schedules}
              onUpdate={onUpdateSchedule}
            />
          </div>
        </>
      )}

      {/* Advanced Settings */}
      <div className="p-4">
        <button
          onClick={() => setShowAdvanced(!showAdvanced)}
          className="flex items-center justify-between w-full text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white"
        >
          <div className="flex items-center gap-2">
            <Cog6ToothIcon className="w-4 h-4" />
            <span>Configuracion Avanzada</span>
          </div>
          {showAdvanced ? <ChevronUpIcon className="w-4 h-4" /> : <ChevronDownIcon className="w-4 h-4" />}
        </button>

        {showAdvanced && (
          <div className="mt-4 space-y-4">
            {/* Notify on Action */}
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-700 dark:text-gray-300">Notificar al actuar</p>
                <p className="text-xs text-gray-500">Recibir notificacion cuando el agente tome una accion</p>
              </div>
              <button
                onClick={() => onUpdateConfig({ notifyOnAction: !config.notifyOnAction })}
                className={`relative w-11 h-6 rounded-full transition-colors ${
                  config.notifyOnAction ? '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 ${
                  config.notifyOnAction ? 'translate-x-6' : 'translate-x-1'
                }`} />
              </button>
            </div>

            {/* Require Confirmation */}
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-700 dark:text-gray-300">Requerir confirmacion</p>
                <p className="text-xs text-gray-500">Pedir confirmacion antes de ejecutar acciones criticas</p>
              </div>
              <button
                onClick={() => onUpdateConfig({ requireConfirmation: !config.requireConfirmation })}
                className={`relative w-11 h-6 rounded-full transition-colors ${
                  config.requireConfirmation ? '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 ${
                  config.requireConfirmation ? 'translate-x-6' : 'translate-x-1'
                }`} />
              </button>
            </div>

            {/* Max Actions Per Hour */}
            <div>
              <div className="flex items-center justify-between mb-2">
                <p className="text-sm font-medium text-gray-700 dark:text-gray-300">Max acciones por hora</p>
                <span className="text-sm text-gray-500">{config.maxActionsPerHour}</span>
              </div>
              <input
                type="range"
                min={1}
                max={20}
                value={config.maxActionsPerHour}
                onChange={(e) => onUpdateConfig({ maxActionsPerHour: parseInt(e.target.value) })}
                className="w-full"
              />
              <div className="flex justify-between text-xs text-gray-400 mt-1">
                <span>1</span>
                <span>20</span>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default AgentModeSelector;
