/**
 * CommandEditor Component
 *
 * 命令编辑/创建对话框
 * 支持编辑命令名称、描述、模板等
 */

import { useState, useEffect } from 'react';
import { X, Save, 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 { Input } from '../primitives/Input';
import { Switch } from '../primitives/Switch';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../primitives/Select';
import {
  createCommand,
  updateCommand,
  getCommandContent,
  type CreateCommandInput,
  type UpdateCommandInput,
  type CommandContent,
} from '../api/client.js';

interface CommandEditorProps {
  /** 编辑模式：指定命令名称；创建模式：undefined */
  commandName?: string;
  /** 关闭回调 */
  onClose: () => void;
  /** 保存成功回调 */
  onSaved?: () => void;
  /** 是否启用响应式布局 */
  responsive?: boolean;
}

export function CommandEditor({
  commandName,
  onClose,
  onSaved,
  responsive = false,
}: CommandEditorProps) {
  const isEditMode = !!commandName;

  // 表单状态
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [template, setTemplate] = useState('');
  const [agent, setAgent] = useState('');
  const [model, setModel] = useState('');
  const [subtask, setSubtask] = useState(false);
  const [scope, setScope] = useState<'user' | 'project'>('user');

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

  // 编辑模式：加载现有命令
  useEffect(() => {
    if (isEditMode && commandName) {
      setLoading(true);
      setError(null);

      getCommandContent(commandName)
        .then((result) => {
          if (result.success && result.data) {
            const data = result.data;
            setOriginalData(data);
            setName(data.name);
            setDescription(data.description || '');
            setTemplate(data.template);
            setAgent(data.agent || '');
            setModel(data.model || '');
            setSubtask(data.subtask || false);
          } else {
            setError(result.error || 'Failed to load command');
          }
        })
        .catch((err) => {
          setError(err instanceof Error ? err.message : 'Failed to load command');
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [isEditMode, commandName]);

  // 保存命令
  const handleSave = async () => {
    // 验证
    if (!name.trim()) {
      toast.error('Command name is required');
      return;
    }
    if (!template.trim()) {
      toast.error('Template is required');
      return;
    }

    setSaving(true);
    setError(null);

    try {
      if (isEditMode) {
        // 更新模式
        const input: UpdateCommandInput = {
          description: description || undefined,
          template,
          agent: agent || undefined,
          model: model || undefined,
          subtask,
        };

        const result = await updateCommand(commandName!, input);
        if (result.success) {
          toast.success('Command updated');
          onSaved?.();
          onClose();
        } else {
          setError(result.error || 'Failed to update command');
        }
      } else {
        // 创建模式
        const input: CreateCommandInput = {
          name: name.trim(),
          description: description || undefined,
          template,
          agent: agent || undefined,
          model: model || undefined,
          subtask,
          scope,
        };

        const result = await createCommand(input);
        if (result.success) {
          toast.success('Command created');
          onSaved?.();
          onClose();
        } else {
          setError(result.error || 'Failed to create command');
        }
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to save command');
    } finally {
      setSaving(false);
    }
  };

  // 是否为内置命令（不可编辑）
  const isBuiltin = originalData?.source === 'builtin';

  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-auto',
            responsive
              ? 'w-full md:w-full md:max-w-2xl md:mx-4 rounded-t-2xl md:rounded-lg'
              : 'rounded-lg w-full max-w-2xl mx-4'
          )}
        >
          {/* Header */}
          <div
            className={cn(
              'sticky top-0 flex items-center justify-between border-b border-line bg-surface-subtle z-10',
              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" />
            )}
            <h2 className={cn('text-lg font-semibold', responsive && 'mt-2 md:mt-0')}>
              {isEditMode ? `Edit Command: /${commandName}` : 'Create Command'}
            </h2>
            <Button
              variant="ghost"
              size="icon"
              onClick={onClose}
              className={cn(responsive && 'min-w-[44px] min-h-[44px]')}
            >
              <X size={20} />
            </Button>
          </div>

          {/* Content */}
          {loading ? (
            <div className="p-6 flex items-center justify-center">
              <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary-500" />
            </div>
          ) : (
            <div className={cn('space-y-5', responsive ? 'p-4 md:p-6' : 'p-6')}>
              {/* Error */}
              {error && (
                <motion.div
                  initial={{ opacity: 0, y: -10 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="flex items-center gap-2 p-3 bg-red-500/10 border border-red-500/30 rounded-lg text-red-400 text-sm"
                >
                  <AlertCircle size={16} />
                  {error}
                </motion.div>
              )}

              {/* Builtin Warning */}
              {isBuiltin && (
                <div className="flex items-center gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg text-yellow-400 text-sm">
                  <AlertCircle size={16} />
                  Builtin commands cannot be modified
                </div>
              )}

              {/* Name */}
              <div className="space-y-2">
                <label className="block text-sm font-medium text-fg-secondary">
                  Name <span className="text-red-400">*</span>
                </label>
                <Input
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="deploy/staging"
                  disabled={isEditMode || isBuiltin}
                  className="font-mono"
                />
                <p className="text-xs text-fg-subtle">
                  Command name. Use / for nested commands (e.g., deploy/staging)
                </p>
              </div>

              {/* Description */}
              <div className="space-y-2">
                <label className="block text-sm font-medium text-fg-secondary">Description</label>
                <Input
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                  placeholder="Deploy to staging environment"
                  disabled={isBuiltin}
                />
              </div>

              {/* Template */}
              <div className="space-y-2">
                <label className="block text-sm font-medium text-fg-secondary">
                  Template <span className="text-red-400">*</span>
                </label>
                <textarea
                  value={template}
                  onChange={(e) => setTemplate(e.target.value)}
                  placeholder="Please help me with $ARGUMENTS"
                  disabled={isBuiltin}
                  rows={6}
                  className={cn(
                    'w-full px-3 py-2 bg-surface-base border border-line rounded-lg',
                    'text-fg placeholder:text-fg-subtle',
                    'focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent',
                    'font-mono text-sm resize-y',
                    'disabled:opacity-50 disabled:cursor-not-allowed'
                  )}
                />
                <p className="text-xs text-fg-subtle">
                  Template syntax: $ARGUMENTS (all args), $1 $2 (positional), @file (include
                  file), !`cmd` (shell output)
                </p>
              </div>

              {/* Agent & Model */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="block text-sm font-medium text-fg-secondary">Agent</label>
                  <Input
                    value={agent}
                    onChange={(e) => setAgent(e.target.value)}
                    placeholder="code-review"
                    disabled={isBuiltin}
                  />
                  <p className="text-xs text-fg-subtle">Optional agent to use</p>
                </div>

                <div className="space-y-2">
                  <label className="block text-sm font-medium text-fg-secondary">Model</label>
                  <Input
                    value={model}
                    onChange={(e) => setModel(e.target.value)}
                    placeholder="claude-sonnet-4-20250514"
                    disabled={isBuiltin}
                  />
                  <p className="text-xs text-fg-subtle">Optional model override</p>
                </div>
              </div>

              {/* Subtask & Scope */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="flex items-center justify-between p-3 bg-surface-base/50 rounded-lg">
                  <div>
                    <label className="block text-sm font-medium text-fg-secondary">Subtask</label>
                    <p className="text-xs text-fg-subtle">Run as background subtask</p>
                  </div>
                  <Switch checked={subtask} onCheckedChange={setSubtask} disabled={isBuiltin} />
                </div>

                {!isEditMode && (
                  <div className="space-y-2">
                    <label className="block text-sm font-medium text-fg-secondary">Scope</label>
                    <Select
                      value={scope}
                      onValueChange={(v) => setScope(v as 'user' | 'project')}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="user">User (global)</SelectItem>
                        <SelectItem value="project">Project (local)</SelectItem>
                      </SelectContent>
                    </Select>
                    <p className="text-xs text-fg-subtle">Where to store the command</p>
                  </div>
                )}
              </div>

              {/* Source Info (edit mode) */}
              {isEditMode && originalData && (
                <div className="pt-4 border-t border-line">
                  <h3 className="text-sm font-medium text-fg-muted mb-2">Command Info</h3>
                  <div className="grid grid-cols-2 gap-2 text-sm">
                    <div>
                      <span className="text-fg-subtle">Source:</span>
                      <span className="ml-2 text-fg-secondary">{originalData.source}</span>
                    </div>
                    {originalData.sourcePath && (
                      <div className="col-span-2">
                        <span className="text-fg-subtle">Path:</span>
                        <span className="ml-2 text-fg-secondary font-mono text-xs break-all">
                          {originalData.sourcePath}
                        </span>
                      </div>
                    )}
                  </div>
                </div>
              )}
            </div>
          )}

          {/* Footer */}
          <div
            className={cn(
              'sticky bottom-0 border-t border-line bg-surface-subtle',
              responsive
                ? 'flex flex-col-reverse md:flex-row items-stretch md:items-center justify-end gap-2 md:gap-3 p-4 md:px-6 md:py-4 safe-area-pb'
                : 'flex items-center justify-end gap-3 px-6 py-4'
            )}
          >
            <Button
              variant="secondary"
              onClick={onClose}
              className={cn(responsive && 'justify-center')}
            >
              Cancel
            </Button>
            {!isBuiltin && (
              <Button
                onClick={handleSave}
                disabled={saving || loading}
                className={cn(responsive && 'justify-center')}
              >
                <Save size={16} className="mr-2" />
                {saving ? 'Saving...' : isEditMode ? 'Update' : 'Create'}
              </Button>
            )}
          </div>
        </motion.div>
      </motion.div>
    </AnimatePresence>
  );
}
