import { useState, useEffect, useCallback } from 'react';
import {
  listRules,
  listScenes,
  createRule,
  createScene,
  updateRule,
  updateScene,
  deleteRule,
  deleteScene,
  triggerRule,
  executeScene,
  toggleRule,
  type AutomationRule,
  type AutomationScene,
} from '@/api/automation';

interface AutomationPanelProps {
  onClose: () => void;
}

/** 触发类型中文映射 */
const TRIGGER_LABELS: Record<string, string> = {
  schedule: '⏰ 定时',
  device_state: '📡 设备状态',
  manual: '🖐️ 手动',
};

/** 触发类型颜色 */
const TRIGGER_COLORS: Record<string, string> = {
  schedule: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
  device_state: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400',
  manual: 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400',
};

/** JSON 安全格式化 */
function safeJSON(raw: unknown, fallback = '-'): string {
  if (!raw) return fallback;
  try {
    if (typeof raw === 'string') return raw;
    return JSON.stringify(raw, null, 1);
  } catch {
    return fallback;
  }
}

/** 格式化时间 */
function formatTime(ts: string): string {
  try {
    const d = new Date(ts);
    return d.toLocaleString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    });
  } catch {
    return ts;
  }
}

/** 默认动作模板 */
const DEFAULT_ACTIONS = [
  {
    type: 'set_device',
    device_id: '',
    property: '',
    value: '',
  },
];

/** 默认定时触发配置模板 */
const DEFAULT_SCHEDULE_TRIGGER = {
  time: '08:00',
  days: ['mon', 'tue', 'wed', 'thu', 'fri'],
};

export function AutomationPanel({ onClose }: AutomationPanelProps) {
  const [activeTab, setActiveTab] = useState<'rules' | 'scenes'>('rules');
  const [viewMode, setViewMode] = useState<'list' | 'create' | 'edit'>('list');

  // 数据
  const [rules, setRules] = useState<AutomationRule[]>([]);
  const [scenes, setScenes] = useState<AutomationScene[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [successMsg, setSuccessMsg] = useState('');

  // 规则表单
  const [editingRuleId, setEditingRuleId] = useState<string | null>(null);
  const [formName, setFormName] = useState('');
  const [formDesc, setFormDesc] = useState('');
  const [formTriggerType, setFormTriggerType] = useState('schedule');
  const [formTriggerConfig, setFormTriggerConfig] = useState(JSON.stringify(DEFAULT_SCHEDULE_TRIGGER, null, 2));
  const [formConditions, setFormConditions] = useState('');
  const [formActions, setFormActions] = useState(JSON.stringify(DEFAULT_ACTIONS, null, 2));
  const [submitting, setSubmitting] = useState(false);

  // 场景表单
  const [editingSceneId, setEditingSceneId] = useState<string | null>(null);
  const [sceneFormName, setSceneFormName] = useState('');
  const [sceneFormIcon, setSceneFormIcon] = useState('🏠');
  const [sceneFormRuleIds, setSceneFormRuleIds] = useState('');
  const [sceneSubmitting, setSceneSubmitting] = useState(false);

  // 展开的规则详情
  const [expandedRuleId, setExpandedRuleId] = useState<string | null>(null);

  const showSuccess = (msg: string) => {
    setSuccessMsg(msg);
    setTimeout(() => setSuccessMsg(''), 2000);
  };

  // 加载数据
  const loadData = useCallback(async () => {
    setLoading(true);
    setError('');
    const [rulesResp, scenesResp] = await Promise.all([listRules(), listScenes()]);
    if (rulesResp.error) {
      setError(rulesResp.error);
    } else {
      setRules(rulesResp.data?.rules ?? []);
    }
    if (scenesResp.error) {
      // 不影响规则列表显示
    } else {
      setScenes(scenesResp.data?.scenes ?? []);
    }
    setLoading(false);
  }, []);

  useEffect(() => {
    loadData();
  }, [loadData]);

  // 重置规则表单
  const resetRuleForm = () => {
    setEditingRuleId(null);
    setFormName('');
    setFormDesc('');
    setFormTriggerType('schedule');
    setFormTriggerConfig(JSON.stringify(DEFAULT_SCHEDULE_TRIGGER, null, 2));
    setFormConditions('');
    setFormActions(JSON.stringify(DEFAULT_ACTIONS, null, 2));
  };

  // 打开规则编辑
  const openRuleEdit = (rule: AutomationRule) => {
    setEditingRuleId(rule.id);
    setFormName(rule.name);
    setFormDesc(rule.description || '');
    setFormTriggerType(rule.trigger_type);
    setFormTriggerConfig(safeJSON(rule.trigger_config, '{}'));
    setFormConditions(safeJSON(rule.conditions, ''));
    setFormActions(safeJSON(rule.actions, '[]'));
    setViewMode('edit');
  };

  // 提交规则表单
  const handleRuleSubmit = async () => {
    if (!formName.trim()) return;
    setSubmitting(true);
    setError('');

    let triggerConfig: unknown = undefined;
    let conditions: unknown = undefined;
    let actions: unknown = undefined;

    try {
      if (formTriggerConfig.trim()) triggerConfig = JSON.parse(formTriggerConfig);
    } catch {
      setError('触发配置 JSON 格式错误');
      setSubmitting(false);
      return;
    }
    try {
      if (formConditions.trim()) conditions = JSON.parse(formConditions);
    } catch {
      setError('条件配置 JSON 格式错误');
      setSubmitting(false);
      return;
    }
    try {
      actions = JSON.parse(formActions);
    } catch {
      setError('动作配置 JSON 格式错误');
      setSubmitting(false);
      return;
    }

    if (editingRuleId) {
      const resp = await updateRule(editingRuleId, {
        name: formName.trim(),
        description: formDesc.trim(),
        trigger_type: formTriggerType,
        trigger_config: triggerConfig,
        conditions,
        actions,
      });
      if (resp.error) {
        setError(resp.error);
      } else {
        showSuccess('规则已更新');
        resetRuleForm();
        setViewMode('list');
        loadData();
      }
    } else {
      const resp = await createRule({
        name: formName.trim(),
        description: formDesc.trim(),
        trigger_type: formTriggerType,
        trigger_config: triggerConfig,
        conditions,
        actions,
      });
      if (resp.error) {
        setError(resp.error);
      } else {
        showSuccess('规则已创建');
        resetRuleForm();
        setViewMode('list');
        loadData();
      }
    }
    setSubmitting(false);
  };

  // 删除规则
  const handleDeleteRule = async (id: string) => {
    if (!confirm('确定要删除这条规则吗？')) return;
    const resp = await deleteRule(id);
    if (resp.error) {
      setError(resp.error);
    } else {
      showSuccess('规则已删除');
      loadData();
    }
  };

  // 手动触发规则
  const handleTriggerRule = async (id: string) => {
    const resp = await triggerRule(id);
    if (resp.error) {
      setError(resp.error);
    } else {
      showSuccess('规则已触发');
    }
  };

  // 切换规则启用状态
  const handleToggleRule = async (rule: AutomationRule) => {
    const resp = await toggleRule(rule.id, !rule.enabled);
    if (resp.error) {
      setError(resp.error);
    } else {
      showSuccess(rule.enabled ? '规则已禁用' : '规则已启用');
      loadData();
    }
  };

  // 重置场景表单
  const resetSceneForm = () => {
    setEditingSceneId(null);
    setSceneFormName('');
    setSceneFormIcon('🏠');
    setSceneFormRuleIds('');
  };

  // 打开场景编辑
  const openSceneEdit = (scene: AutomationScene) => {
    setEditingSceneId(scene.id);
    setSceneFormName(scene.name);
    setSceneFormIcon(scene.icon || '🏠');
    setSceneFormRuleIds(safeJSON(scene.rule_ids, ''));
    setViewMode('edit');
  };

  // 提交场景表单
  const handleSceneSubmit = async () => {
    if (!sceneFormName.trim()) return;
    setSceneSubmitting(true);
    setError('');

    let ruleIds: string[] | undefined = undefined;
    try {
      if (sceneFormRuleIds.trim()) {
        ruleIds = JSON.parse(sceneFormRuleIds);
      }
    } catch {
      setError('规则 ID 列表 JSON 格式错误');
      setSceneSubmitting(false);
      return;
    }

    if (editingSceneId) {
      const resp = await updateScene(editingSceneId, {
        name: sceneFormName.trim(),
        icon: sceneFormIcon,
        rule_ids: ruleIds,
      });
      if (resp.error) {
        setError(resp.error);
      } else {
        showSuccess('场景已更新');
        resetSceneForm();
        setViewMode('list');
        loadData();
      }
    } else {
      const resp = await createScene({
        name: sceneFormName.trim(),
        icon: sceneFormIcon,
        rule_ids: ruleIds,
      });
      if (resp.error) {
        setError(resp.error);
      } else {
        showSuccess('场景已创建');
        resetSceneForm();
        setViewMode('list');
        loadData();
      }
    }
    setSceneSubmitting(false);
  };

  // 删除场景
  const handleDeleteScene = async (id: string) => {
    if (!confirm('确定要删除这个场景吗？')) return;
    const resp = await deleteScene(id);
    if (resp.error) {
      setError(resp.error);
    } else {
      showSuccess('场景已删除');
      loadData();
    }
  };

  // 执行场景
  const handleExecuteScene = async (id: string) => {
    const resp = await executeScene(id);
    if (resp.error) {
      setError(resp.error);
    } else {
      showSuccess('场景已执行');
    }
  };

  // 获取规则名称映射
  const ruleNameMap: Record<string, string> = {};
  rules.forEach((r) => { ruleNameMap[r.id] = r.name; });

  // 解析场景中的规则列表
  const getSceneRuleNames = (scene: AutomationScene): string[] => {
    if (!scene.rule_ids) return [];
    try {
      const ids: string[] = typeof scene.rule_ids === 'string'
        ? JSON.parse(scene.rule_ids)
        : (scene.rule_ids as string[]);
      return ids.map((id) => ruleNameMap[id] || id);
    } catch {
      return [];
    }
  };

  return (
    <div className="w-full max-h-full flex flex-col">
      {/* 顶部 Tab 切换 */}
      <div className="flex items-center border-b border-gray-100 dark:border-gray-700">
        <button
          onClick={() => { setActiveTab('rules'); setViewMode('list'); }}
          className={`flex-1 py-2.5 text-xs font-medium transition-colors ${
            activeTab === 'rules'
              ? 'text-pink-500 border-b-2 border-pink-500'
              : 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'
          }`}
        >
          规则
        </button>
        <button
          onClick={() => { setActiveTab('scenes'); setViewMode('list'); }}
          className={`flex-1 py-2.5 text-xs font-medium transition-colors ${
            activeTab === 'scenes'
              ? 'text-pink-500 border-b-2 border-pink-500'
              : 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'
          }`}
        >
          场景
        </button>
      </div>

      {/* 消息提示 */}
      {successMsg && (
        <div className="px-3 py-2 text-xs text-green-600 bg-green-50 dark:bg-green-900/20 dark:text-green-400">
          ✅ {successMsg}
        </div>
      )}
      {error && (
        <div className="px-3 py-2 text-xs text-red-500 bg-red-50 dark:bg-red-900/20">
          ⚠️ {error}
          <button
            onClick={() => setError('')}
            className="ml-2 underline hover:no-underline"
          >
            关闭
          </button>
        </div>
      )}

      {/* ========== 规则面板 ========== */}
      {activeTab === 'rules' && (
        <>
          {/* 列表模式 */}
          {viewMode === 'list' && (
            <>
              <div className="flex items-center justify-between px-3 py-2 border-b border-gray-50 dark:border-gray-700">
                <span className="text-[10px] text-gray-400">
                  {rules.length} 条规则
                </span>
                <button
                  onClick={() => { resetRuleForm(); setViewMode('create'); }}
                  className="px-2.5 py-1 text-[11px] bg-pink-500 text-white rounded-full hover:bg-pink-600 transition-colors"
                >
                  + 新建规则
                </button>
              </div>

              <div className="overflow-y-auto max-h-72">
                {loading ? (
                  <div className="px-4 py-8 text-center text-sm text-gray-400">
                    ⏳ 加载中...
                  </div>
                ) : rules.length === 0 ? (
                  <div className="px-4 py-8 text-center text-sm text-gray-400">
                    ⚡ 暂无自动化规则，点击「+ 新建规则」创建
                  </div>
                ) : (
                  <div className="divide-y divide-gray-50 dark:divide-gray-700">
                    {rules.map((rule) => (
                      <div key={rule.id} className="px-3 py-2.5">
                        <div className="flex items-start justify-between gap-2">
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2">
                              <button
                                onClick={() => handleToggleRule(rule)}
                                className={`relative inline-flex h-4 w-8 items-center rounded-full transition-colors flex-shrink-0 ${
                                  rule.enabled ? 'bg-pink-500' : 'bg-gray-300 dark:bg-gray-600'
                                }`}
                              >
                                <span
                                  className={`inline-block h-3 w-3 rounded-full bg-white transition-transform ${
                                    rule.enabled ? 'translate-x-[18px]' : 'translate-x-[2px]'
                                  }`}
                                />
                              </button>
                              <span className={`text-sm truncate ${rule.enabled ? 'text-gray-800 dark:text-gray-200' : 'text-gray-400'}`}>
                                {rule.name}
                              </span>
                            </div>
                            <div className="flex items-center gap-2 mt-1">
                              <span className={`text-[10px] px-1.5 py-0.5 rounded-full ${TRIGGER_COLORS[rule.trigger_type] || 'bg-gray-100 text-gray-600'}`}>
                                {TRIGGER_LABELS[rule.trigger_type] || rule.trigger_type}
                              </span>
                              {rule.last_triggered_at && (
                                <span className="text-[10px] text-gray-400">
                                  上次: {formatTime(rule.last_triggered_at)}
                                </span>
                              )}
                            </div>
                          </div>

                          <div className="flex items-center gap-0.5 flex-shrink-0">
                            {rule.trigger_type === 'manual' && (
                              <button
                                onClick={() => handleTriggerRule(rule.id)}
                                title="手动触发"
                                className="p-1 text-gray-300 hover:text-green-500 transition-colors"
                              >
                                <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                              </button>
                            )}
                            <button
                              onClick={() => openRuleEdit(rule)}
                              title="编辑"
                              className="p-1 text-gray-300 hover:text-blue-500 transition-colors"
                            >
                              <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                              </svg>
                            </button>
                            <button
                              onClick={() => handleDeleteRule(rule.id)}
                              title="删除"
                              className="p-1 text-gray-300 hover:text-red-500 transition-colors"
                            >
                              <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                              </svg>
                            </button>
                          </div>
                        </div>

                        {/* 展开详情 */}
                        {expandedRuleId === rule.id && (
                          <div className="mt-2 pl-8 space-y-1 text-[11px] text-gray-500 dark:text-gray-400">
                            {rule.description && (
                              <p>📝 {rule.description}</p>
                            )}
                            <p className="whitespace-pre-wrap font-mono text-[10px] bg-gray-50 dark:bg-gray-750 p-1 rounded">
                              触发: {safeJSON(rule.trigger_config)}
                            </p>
                            {rule.conditions != null && (
                              <p className="whitespace-pre-wrap font-mono text-[10px] bg-gray-50 dark:bg-gray-750 p-1 rounded">
                                条件: {safeJSON(rule.conditions)}
                              </p>
                            )}
                            <p className="whitespace-pre-wrap font-mono text-[10px] bg-gray-50 dark:bg-gray-750 p-1 rounded">
                              动作: {safeJSON(rule.actions)}
                            </p>
                          </div>
                        )}
                        <button
                          onClick={() => setExpandedRuleId(expandedRuleId === rule.id ? null : rule.id)}
                          className="mt-1 ml-8 text-[10px] text-pink-400 hover:text-pink-500"
                        >
                          {expandedRuleId === rule.id ? '收起 ▲' : '展开 ▼'}
                        </button>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </>
          )}

          {/* 创建/编辑规则表单 */}
          {(viewMode === 'create' || viewMode === 'edit') && (
            <div className="p-3 space-y-3 overflow-y-auto max-h-80">
              <div className="flex items-center justify-between">
                <span className="text-xs font-medium text-gray-600 dark:text-gray-300">
                  {editingRuleId ? '编辑规则' : '新建规则'}
                </span>
                <button
                  onClick={() => { setViewMode('list'); resetRuleForm(); }}
                  className="text-[10px] text-gray-400 hover:text-gray-600"
                >
                  返回列表
                </button>
              </div>

              <div>
                <label className="block text-xs text-gray-500 dark:text-gray-400 mb-1">名称 *</label>
                <input
                  type="text"
                  value={formName}
                  onChange={(e) => setFormName(e.target.value)}
                  placeholder="例如：夜间自动关灯"
                  maxLength={200}
                  className="w-full px-3 py-1.5 text-sm border border-gray-200 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-800 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-pink-400"
                />
              </div>

              <div>
                <label className="block text-xs text-gray-500 dark:text-gray-400 mb-1">描述</label>
                <textarea
                  value={formDesc}
                  onChange={(e) => setFormDesc(e.target.value)}
                  placeholder="规则的用途说明"
                  rows={2}
                  maxLength={500}
                  className="w-full px-3 py-1.5 text-sm border border-gray-200 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-800 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-pink-400 resize-none"
                />
              </div>

              <div>
                <label className="block text-xs text-gray-500 dark:text-gray-400 mb-1">触发类型</label>
                <select
                  value={formTriggerType}
                  onChange={(e) => setFormTriggerType(e.target.value)}
                  className="w-full px-3 py-1.5 text-sm border border-gray-200 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-800 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-pink-400"
                >
                  <option value="schedule">定时 (schedule)</option>
                  <option value="device_state">设备状态 (device_state)</option>
                  <option value="manual">手动 (manual)</option>
                </select>
              </div>

              <div>
                <label className="block text-xs text-gray-500 dark:text-gray-400 mb-1">触发配置 (JSON)</label>
                <textarea
                  value={formTriggerConfig}
                  onChange={(e) => setFormTriggerConfig(e.target.value)}
                  placeholder='{"time":"08:00","days":["mon","tue"]}'
                  rows={3}
                  className="w-full px-3 py-1.5 text-xs font-mono border border-gray-200 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-750 text-gray-800 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-pink-400 resize-none"
                />
              </div>

              <div>
                <label className="block text-xs text-gray-500 dark:text-gray-400 mb-1">条件 (JSON, 可选)</label>
                <textarea
                  value={formConditions}
                  onChange={(e) => setFormConditions(e.target.value)}
                  placeholder='[{"type":"time_range","start":"22:00","end":"06:00"}]'
                  rows={3}
                  className="w-full px-3 py-1.5 text-xs font-mono border border-gray-200 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-750 text-gray-800 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-pink-400 resize-none"
                />
              </div>

              <div>
                <label className="block text-xs text-gray-500 dark:text-gray-400 mb-1">动作 (JSON) *</label>
                <textarea
                  value={formActions}
                  onChange={(e) => setFormActions(e.target.value)}
                  placeholder='[{"type":"set_device","device_id":"","property":"","value":""}]'
                  rows={4}
                  className="w-full px-3 py-1.5 text-xs font-mono border border-gray-200 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-750 text-gray-800 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-pink-400 resize-none"
                />
              </div>

              <div className="flex gap-2">
                <button
                  onClick={() => { setViewMode('list'); resetRuleForm(); }}
                  className="flex-1 py-1.5 text-xs border border-gray-200 dark:border-gray-600 rounded-lg text-gray-500 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
                >
                  取消
                </button>
                <button
                  onClick={handleRuleSubmit}
                  disabled={submitting || !formName.trim() || !formActions.trim()}
                  className="flex-1 py-1.5 text-xs bg-pink-500 text-white rounded-lg hover:bg-pink-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  {submitting ? '保存中...' : editingRuleId ? '更新规则' : '创建规则'}
                </button>
              </div>
            </div>
          )}
        </>
      )}

      {/* ========== 场景面板 ========== */}
      {activeTab === 'scenes' && (
        <>
          {viewMode === 'list' && (
            <>
              <div className="flex items-center justify-between px-3 py-2 border-b border-gray-50 dark:border-gray-700">
                <span className="text-[10px] text-gray-400">
                  {scenes.length} 个场景
                </span>
                <button
                  onClick={() => { resetSceneForm(); setViewMode('create'); }}
                  className="px-2.5 py-1 text-[11px] bg-pink-500 text-white rounded-full hover:bg-pink-600 transition-colors"
                >
                  + 新建场景
                </button>
              </div>

              <div className="overflow-y-auto max-h-72">
                {loading ? (
                  <div className="px-4 py-8 text-center text-sm text-gray-400">
                    ⏳ 加载中...
                  </div>
                ) : scenes.length === 0 ? (
                  <div className="px-4 py-8 text-center text-sm text-gray-400">
                    🎬 暂无场景，点击「+ 新建场景」创建
                  </div>
                ) : (
                  <div className="divide-y divide-gray-50 dark:divide-gray-700">
                    {scenes.map((scene) => {
                      const ruleNames = getSceneRuleNames(scene);
                      return (
                        <div key={scene.id} className="px-3 py-2.5">
                          <div className="flex items-start justify-between gap-2">
                            <div className="flex-1 min-w-0">
                              <div className="flex items-center gap-2">
                                <span className="text-lg">{scene.icon || '🏠'}</span>
                                <span className="text-sm text-gray-800 dark:text-gray-200 truncate">
                                  {scene.name}
                                </span>
                              </div>
                              {ruleNames.length > 0 && (
                                <div className="flex flex-wrap gap-1 mt-1 ml-8">
                                  {ruleNames.map((name, i) => (
                                    <span
                                      key={i}
                                      className="text-[10px] px-1.5 py-0.5 bg-pink-50 dark:bg-pink-900/20 text-pink-600 dark:text-pink-400 rounded-full"
                                    >
                                      {name}
                                    </span>
                                  ))}
                                </div>
                              )}
                              <span className="text-[10px] text-gray-400 ml-8 mt-1 block">
                                创建于 {formatTime(scene.created_at)}
                              </span>
                            </div>

                            <div className="flex items-center gap-0.5 flex-shrink-0">
                              <button
                                onClick={() => handleExecuteScene(scene.id)}
                                title="执行场景"
                                className="p-1 text-gray-300 hover:text-green-500 transition-colors"
                              >
                                <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                              </button>
                              <button
                                onClick={() => openSceneEdit(scene)}
                                title="编辑"
                                className="p-1 text-gray-300 hover:text-blue-500 transition-colors"
                              >
                                <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                </svg>
                              </button>
                              <button
                                onClick={() => handleDeleteScene(scene.id)}
                                title="删除"
                                className="p-1 text-gray-300 hover:text-red-500 transition-colors"
                              >
                                <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                </svg>
                              </button>
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            </>
          )}

          {/* 创建/编辑场景表单 */}
          {(viewMode === 'create' || viewMode === 'edit') && (
            <div className="p-3 space-y-3 overflow-y-auto max-h-80">
              <div className="flex items-center justify-between">
                <span className="text-xs font-medium text-gray-600 dark:text-gray-300">
                  {editingSceneId ? '编辑场景' : '新建场景'}
                </span>
                <button
                  onClick={() => { setViewMode('list'); resetSceneForm(); }}
                  className="text-[10px] text-gray-400 hover:text-gray-600"
                >
                  返回列表
                </button>
              </div>

              <div>
                <label className="block text-xs text-gray-500 dark:text-gray-400 mb-1">名称 *</label>
                <input
                  type="text"
                  value={sceneFormName}
                  onChange={(e) => setSceneFormName(e.target.value)}
                  placeholder="例如：回家模式"
                  maxLength={200}
                  className="w-full px-3 py-1.5 text-sm border border-gray-200 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-800 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-pink-400"
                />
              </div>

              <div>
                <label className="block text-xs text-gray-500 dark:text-gray-400 mb-1">图标</label>
                <input
                  type="text"
                  value={sceneFormIcon}
                  onChange={(e) => setSceneFormIcon(e.target.value)}
                  placeholder="🏠"
                  maxLength={10}
                  className="w-full px-3 py-1.5 text-sm border border-gray-200 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-800 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-pink-400"
                />
              </div>

              <div>
                <label className="block text-xs text-gray-500 dark:text-gray-400 mb-1">
                  规则 ID 列表 (JSON 数组)
                </label>
                <textarea
                  value={sceneFormRuleIds}
                  onChange={(e) => setSceneFormRuleIds(e.target.value)}
                  placeholder='["rule_id_1","rule_id_2"]'
                  rows={3}
                  className="w-full px-3 py-1.5 text-xs font-mono border border-gray-200 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-750 text-gray-800 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-pink-400 resize-none"
                />
                {rules.length > 0 && (
                  <div className="mt-1 flex flex-wrap gap-1">
                    <span className="text-[10px] text-gray-400">可用规则：</span>
                    {rules.map((r) => (
                      <button
                        key={r.id}
                        onClick={() => {
                          try {
                            const ids: string[] = sceneFormRuleIds.trim()
                              ? JSON.parse(sceneFormRuleIds)
                              : [];
                            if (!ids.includes(r.id)) {
                              setSceneFormRuleIds(JSON.stringify([...ids, r.id]));
                            }
                          } catch {
                            setSceneFormRuleIds(JSON.stringify([r.id]));
                          }
                        }}
                        className="text-[10px] px-1.5 py-0.5 bg-gray-100 dark:bg-gray-700 rounded hover:bg-pink-100 dark:hover:bg-pink-900/30 transition-colors"
                        title={r.id}
                      >
                        {r.name}
                      </button>
                    ))}
                  </div>
                )}
              </div>

              <div className="flex gap-2">
                <button
                  onClick={() => { setViewMode('list'); resetSceneForm(); }}
                  className="flex-1 py-1.5 text-xs border border-gray-200 dark:border-gray-600 rounded-lg text-gray-500 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
                >
                  取消
                </button>
                <button
                  onClick={handleSceneSubmit}
                  disabled={sceneSubmitting || !sceneFormName.trim()}
                  className="flex-1 py-1.5 text-xs bg-pink-500 text-white rounded-lg hover:bg-pink-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  {sceneSubmitting ? '保存中...' : editingSceneId ? '更新场景' : '创建场景'}
                </button>
              </div>
            </div>
          )}
        </>
      )}
    </div>
  );
}
