/**
 * AgentDefaultsEditor Component
 *
 * 全局默认配置编辑器：配置所有 Agent 的默认参数
 */

import { useState, useEffect } from 'react';
import {
  X,
  Save,
  Settings,
  AlertCircle,
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { toast } from 'sonner';
import { cn } from '../utils/cn';
import { modalOverlay, modalContent, smoothTransition } from '../utils/animations';
import { Button } from '../primitives/Button';
import {
  getAgentDefaults,
  updateAgentDefaults,
  type AgentDefaults,
  type AgentModelConfig,
} from '../api/client.js';

interface AgentDefaultsEditorProps {
  onClose: () => void;
  onSave: () => void;
  /** 是否启用响应式布局 */
  responsive?: boolean;
}

export function AgentDefaultsEditor({
  onClose,
  onSave,
  responsive = false,
}: AgentDefaultsEditorProps) {
  // 表单状态
  const [maxSteps, setMaxSteps] = useState<number | undefined>(undefined);

  // 模型配置
  const [modelProvider, setModelProvider] = useState<string>('');
  const [modelName, setModelName] = useState('');
  const [temperature, setTemperature] = useState<number | undefined>(undefined);
  const [maxTokens, setMaxTokens] = useState<number | undefined>(undefined);

  // Vision 模型配置
  const [visionProvider, setVisionProvider] = useState<string>('');
  const [visionModel, setVisionModel] = useState('');

  // UI 状态
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 加载现有配置
  useEffect(() => {
    const loadDefaults = async () => {
      setLoading(true);
      try {
        const result = await getAgentDefaults();
        if (result.success && result.data) {
          const defaults = result.data;

          setMaxSteps(defaults.maxSteps);

          if (defaults.model) {
            setModelProvider(defaults.model.provider || '');
            setModelName(defaults.model.model || '');
            setTemperature(defaults.model.temperature);
            setMaxTokens(defaults.model.maxTokens);
          }

          if (defaults.vision) {
            setVisionProvider(defaults.vision.provider || '');
            setVisionModel(defaults.vision.model || '');
          }
        }
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load defaults');
      } finally {
        setLoading(false);
      }
    };

    loadDefaults();
  }, []);

  // 构建配置对象
  const buildDefaults = (): AgentDefaults => {
    const defaults: AgentDefaults = {};

    if (maxSteps !== undefined) {
      defaults.maxSteps = maxSteps;
    }

    // 模型配置
    const model: AgentModelConfig = {};
    if (modelProvider) {
      model.provider = modelProvider as 'anthropic' | 'deepseek' | 'openai';
    }
    if (modelName) {
      model.model = modelName;
    }
    if (temperature !== undefined) {
      model.temperature = temperature;
    }
    if (maxTokens !== undefined) {
      model.maxTokens = maxTokens;
    }
    if (Object.keys(model).length > 0) {
      defaults.model = model;
    }

    // Vision 配置
    const vision: AgentModelConfig = {};
    if (visionProvider) {
      vision.provider = visionProvider as 'anthropic' | 'deepseek' | 'openai';
    }
    if (visionModel) {
      vision.model = visionModel;
    }
    if (Object.keys(vision).length > 0) {
      defaults.vision = vision;
    }

    return defaults;
  };

  // 保存
  const handleSave = async () => {
    setSaving(true);
    setError(null);

    try {
      const defaults = buildDefaults();
      const result = await updateAgentDefaults(defaults);

      if (result.success) {
        toast.success('Default settings saved');
        onSave();
      } else {
        setError(result.error || 'Save failed');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Save failed');
    } finally {
      setSaving(false);
    }
  };

  return (
    <AnimatePresence>
      <motion.div
        variants={modalOverlay}
        initial="initial"
        animate="animate"
        exit="exit"
        transition={{ duration: 0.2 }}
        className={cn(
          'fixed inset-0 bg-black/50 flex z-50',
          responsive ? 'items-end md:items-center justify-center' : 'items-center justify-center'
        )}
        onClick={onClose}
      >
        <motion.div
          variants={modalContent}
          initial="initial"
          animate="animate"
          exit="exit"
          transition={smoothTransition}
          onClick={(e) => e.stopPropagation()}
          className={cn(
            'bg-surface-subtle max-h-[90vh] overflow-hidden flex flex-col',
            responsive
              ? 'w-full md:w-full md:max-w-lg md:mx-4 rounded-t-2xl md:rounded-lg'
              : 'rounded-lg w-full max-w-lg mx-4'
          )}
        >
          {/* Header */}
          <div
            className={cn(
              'flex items-center justify-between border-b border-line',
              responsive ? 'px-4 md:px-6 py-4' : 'px-6 py-4'
            )}
          >
            {responsive && (
              <div className="absolute top-2 left-1/2 -translate-x-1/2 w-10 h-1 bg-surface-emphasis rounded-full md:hidden" />
            )}
            <div className={cn(responsive && 'mt-2 md:mt-0')}>
              <h2 className="text-lg font-semibold flex items-center gap-2">
                <Settings size={20} className="text-primary-400" />
                Global Defaults
              </h2>
              <p className="text-xs text-fg-subtle">
                These settings apply to all agents unless overridden
              </p>
            </div>
            <Button
              variant="ghost"
              size="icon"
              onClick={onClose}
              className={cn(responsive && 'min-w-[44px] min-h-[44px]')}
            >
              <X size={20} />
            </Button>
          </div>

          {/* Content */}
          <div className="flex-1 overflow-y-auto p-4 space-y-6">
            {loading ? (
              <div className="flex items-center justify-center py-12">
                <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary-500" />
              </div>
            ) : (
              <>
                {/* Error */}
                {error && (
                  <div className="flex items-start gap-2 p-3 bg-red-500/10 border border-red-500/30 rounded-lg text-red-400 text-sm">
                    <AlertCircle size={16} className="mt-0.5 flex-shrink-0" />
                    <span>{error}</span>
                  </div>
                )}

                {/* Execution Limits */}
                <div className="space-y-4">
                  <h3 className="text-sm font-medium text-fg-secondary">Execution Limits</h3>
                  <div>
                    <label className="block text-xs text-fg-muted mb-1">Default Max Steps</label>
                    <input
                      type="number"
                      value={maxSteps ?? ''}
                      onChange={(e) =>
                        setMaxSteps(e.target.value ? parseInt(e.target.value) : undefined)
                      }
                      placeholder="15"
                      min="1"
                      className="w-full px-3 py-2 bg-surface-base border border-line rounded-lg text-sm focus:outline-none focus:border-primary-500"
                    />
                    <p className="text-xs text-fg-subtle mt-1">
                      Maximum number of tool call steps for all agents
                    </p>
                  </div>
                </div>

                {/* Model Configuration */}
                <div className="space-y-4">
                  <h3 className="text-sm font-medium text-fg-secondary">Default Model</h3>
                  <p className="text-xs text-fg-subtle -mt-2">
                    The main model used for all conversations
                  </p>
                  <div className="grid grid-cols-2 gap-4">
                    {/* Provider */}
                    <div>
                      <label className="block text-xs text-fg-muted mb-1">Provider</label>
                      <select
                        value={modelProvider}
                        onChange={(e) => setModelProvider(e.target.value)}
                        className="w-full px-3 py-2 bg-surface-base border border-line rounded-lg text-sm focus:outline-none focus:border-primary-500"
                      >
                        <option value="">Default</option>
                        <option value="anthropic">Anthropic</option>
                        <option value="openai">OpenAI</option>
                        <option value="deepseek">DeepSeek</option>
                      </select>
                    </div>

                    {/* Model */}
                    <div>
                      <label className="block text-xs text-fg-muted mb-1">Model</label>
                      <input
                        type="text"
                        value={modelName}
                        onChange={(e) => setModelName(e.target.value)}
                        placeholder="claude-sonnet-4-20250514"
                        className="w-full px-3 py-2 bg-surface-base border border-line rounded-lg text-sm focus:outline-none focus:border-primary-500"
                      />
                    </div>

                    {/* Temperature */}
                    <div>
                      <label className="block text-xs text-fg-muted mb-1">Temperature</label>
                      <input
                        type="number"
                        value={temperature ?? ''}
                        onChange={(e) =>
                          setTemperature(e.target.value ? parseFloat(e.target.value) : undefined)
                        }
                        placeholder="0.7"
                        min="0"
                        max="1"
                        step="0.1"
                        className="w-full px-3 py-2 bg-surface-base border border-line rounded-lg text-sm focus:outline-none focus:border-primary-500"
                      />
                    </div>

                    {/* Max Tokens */}
                    <div>
                      <label className="block text-xs text-fg-muted mb-1">Max Tokens</label>
                      <input
                        type="number"
                        value={maxTokens ?? ''}
                        onChange={(e) =>
                          setMaxTokens(e.target.value ? parseInt(e.target.value) : undefined)
                        }
                        placeholder="8192"
                        min="1"
                        className="w-full px-3 py-2 bg-surface-base border border-line rounded-lg text-sm focus:outline-none focus:border-primary-500"
                      />
                    </div>
                  </div>
                </div>

                {/* Vision Model Configuration */}
                <div className="space-y-4">
                  <h3 className="text-sm font-medium text-fg-secondary">Vision Model</h3>
                  <p className="text-xs text-fg-subtle -mt-2">
                    Used for image understanding when the default model doesn't support vision
                  </p>
                  <div className="grid grid-cols-2 gap-4">
                    {/* Vision Provider */}
                    <div>
                      <label className="block text-xs text-fg-muted mb-1">Provider</label>
                      <select
                        value={visionProvider}
                        onChange={(e) => setVisionProvider(e.target.value)}
                        className="w-full px-3 py-2 bg-surface-base border border-line rounded-lg text-sm focus:outline-none focus:border-primary-500"
                      >
                        <option value="">Not configured</option>
                        <option value="anthropic">Anthropic</option>
                        <option value="openai">OpenAI</option>
                      </select>
                    </div>

                    {/* Vision Model */}
                    <div>
                      <label className="block text-xs text-fg-muted mb-1">Model</label>
                      <input
                        type="text"
                        value={visionModel}
                        onChange={(e) => setVisionModel(e.target.value)}
                        placeholder="gpt-4o"
                        className="w-full px-3 py-2 bg-surface-base border border-line rounded-lg text-sm focus:outline-none focus:border-primary-500"
                      />
                    </div>
                  </div>
                </div>

                {/* Info */}
                <div className="p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg text-blue-400 text-xs">
                  <p>
                    These defaults will be applied to all agents. Individual agents can override
                    these settings in their own configuration.
                  </p>
                </div>
              </>
            )}
          </div>

          {/* Footer */}
          <div
            className={cn(
              'border-t border-line flex justify-end gap-2',
              responsive ? 'px-4 py-3 safe-area-pb' : 'px-6 py-3'
            )}
          >
            <Button variant="ghost" onClick={onClose}>
              Cancel
            </Button>
            <Button variant="default" onClick={handleSave} disabled={saving || loading}>
              <Save size={16} className="mr-1" />
              {saving ? 'Saving...' : 'Save'}
            </Button>
          </div>
        </motion.div>
      </motion.div>
    </AnimatePresence>
  );
}
