import React, { useState, useEffect } from 'react';
import { Settings, Database, Trash2, Edit3, Plus, Loader2, X } from 'lucide-react';
import { cn } from '../lib/utils';
import { useStore } from '../store/useStore';
import { getTemplates, createTemplate, updateTemplate, deleteTemplate } from '../lib/api';
import type { Template, TemplateClass } from '../store/useStore';

export function TemplateRegistry() {
  const templates = useStore((state) => state.templates);
  const setTemplates = useStore((state) => state.setTemplates);
  const addTemplate = useStore((state) => state.addTemplate);
  const updateTemplateStore = useStore((state) => state.updateTemplate);
  const removeTemplateStore = useStore((state) => state.removeTemplate);

  const [isLoading, setIsLoading] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<Template | null>(null);
  const [showModal, setShowModal] = useState(false);
  const [isSaving, setIsSaving] = useState(false);

  const [editName, setEditName] = useState('');
  const [editDesc, setEditDesc] = useState('');
  const [editClasses, setEditClasses] = useState<TemplateClass[]>([]);
  const [editingClassId, setEditingClassId] = useState<string | null>(null);

  useEffect(() => {
    setIsLoading(true);
    getTemplates()
      .then((data) => setTemplates(data))
      .catch(console.error)
      .finally(() => setIsLoading(false));
  }, [setTemplates]);

  const openCreate = () => {
    setSelectedTemplate(null);
    setEditName('');
    setEditDesc('');
    setEditClasses([]);
    setShowModal(true);
  };

  const openEdit = (template: Template) => {
    setSelectedTemplate(template);
    setEditName(template.name);
    setEditDesc(template.description || '');
    setEditClasses(template.classes ? [...template.classes] : []);
    setShowModal(true);
  };

  const handleSave = async () => {
    if (!editName.trim()) return;
    setIsSaving(true);
    try {
      if (selectedTemplate) {
        const updated = await updateTemplate(selectedTemplate.id, {
          name: editName.trim(),
          description: editDesc.trim() || undefined,
          classes: editClasses,
        });
        updateTemplateStore(updated);
      } else {
        const created = await createTemplate({
          name: editName.trim(),
          description: editDesc.trim() || undefined,
          classes: editClasses,
        });
        addTemplate(created);
      }
      setShowModal(false);
    } catch (err) {
      console.error('Failed to save template:', err);
    } finally {
      setIsSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('确定要删除此模板吗？')) return;
    try {
      await deleteTemplate(id);
      removeTemplateStore(id);
      if (selectedTemplate?.id === id) {
        setSelectedTemplate(null);
      }
    } catch (err) {
      console.error('Failed to delete template:', err);
    }
  };

  const addClass = () => {
    const newClass: TemplateClass = {
      id: `cls-${Date.now()}`,
      name: '新类别',
      color: '#06b6d4',
      zIndex: editClasses.length > 0 ? Math.max(...editClasses.map((c) => c.zIndex)) + 10 : 10,
      category: '未分类',
    };
    setEditClasses([...editClasses, newClass]);
    setEditingClassId(newClass.id);
  };

  const updateClass = (id: string, updates: Partial<TemplateClass>) => {
    setEditClasses(editClasses.map((c) => (c.id === id ? { ...c, ...updates } : c)));
  };

  const removeClass = (id: string) => {
    setEditClasses(editClasses.filter((c) => c.id !== id));
  };

  const activeTemplate = selectedTemplate || templates[0] || null;

  return (
    <div className="p-8 w-full h-full overflow-y-auto bg-[#0a0a0a]">
      <div className="mb-8 border-b border-white/5 pb-6">
        <h1 className="text-3xl font-medium tracking-tight text-white mb-2">分割模板与分类优先级管理库</h1>
        <p className="text-gray-400 text-sm">定义业务语义本体树架构、约束覆盖遮罩优先级(Z-Index裁决权重)，以及真实标签数据的向下兼容转换映射(Dict Translation)原则。</p>
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
        <div className="xl:col-span-1 border-r border-white/5 pr-6">
          <div className="flex justify-between items-center mb-6">
             <h2 className="text-sm font-bold text-gray-500 uppercase tracking-widest">生效中模板架构清单</h2>
             <button 
               onClick={openCreate}
               className="text-cyan-400 hover:text-cyan-300 text-sm transition-colors flex items-center gap-1"
             >
               <Plus size={14} /> 新建方案
             </button>
          </div>

          {isLoading && templates.length === 0 ? (
            <div className="space-y-3">
              {Array.from({ length: 4 }).map((_, i) => (
                <div key={i} className="bg-[#111] border border-white/5 p-4 rounded-xl animate-pulse">
                  <div className="h-4 bg-[#1a1a1a] rounded w-2/3 mb-2" />
                  <div className="h-3 bg-[#1a1a1a] rounded w-1/2" />
                </div>
              ))}
            </div>
          ) : (
            <div className="space-y-3">
               {templates.map((t) => (
                 <div 
                   key={t.id} 
                   className={cn(
                     "bg-[#111] border p-4 rounded-xl cursor-pointer transition-all hover:shadow-lg hover:shadow-cyan-900/10 group",
                     activeTemplate?.id === t.id ? "border-cyan-500/50" : "border-white/5 hover:border-cyan-500/50"
                   )}
                   onClick={() => setSelectedTemplate(t)}
                 >
                   <div className="flex justify-between items-start">
                     <h3 className="font-medium text-gray-200 mb-1">{t.name}</h3>
                     <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                       <button 
                         onClick={(e) => { e.stopPropagation(); openEdit(t); }}
                         className="p-1 rounded text-gray-500 hover:text-cyan-400 transition-colors"
                       >
                         <Edit3 size={14} />
                       </button>
                       <button 
                         onClick={(e) => { e.stopPropagation(); handleDelete(t.id); }}
                         className="p-1 rounded text-gray-500 hover:text-red-400 transition-colors"
                       >
                         <Trash2 size={14} />
                       </button>
                     </div>
                   </div>
                   <div className="flex items-center gap-4 text-xs text-gray-500 font-mono">
                     <span>涵盖 {t.classes?.length ?? 0} 个字典大类</span>
                     <span>挂载 {t.rules?.length ?? 0} 项解析规则</span>
                   </div>
                 </div>
               ))}
            </div>
          )}
        </div>

        <div className="xl:col-span-2 space-y-6">
           <div className="bg-[#111] border border-white/5 rounded-xl p-6">
             <div className="flex items-center justify-between mb-6 border-b border-white/5 pb-4">
                <h2 className="text-lg font-medium text-gray-200 flex items-center gap-2">
                  <Database size={18} /> 
                  {activeTemplate ? activeTemplate.name : '未选择模板'}
                </h2>
                {activeTemplate && (
                  <button 
                    onClick={() => openEdit(activeTemplate)}
                    className="bg-white/5 hover:bg-white/10 border border-white/10 px-4 py-1.5 rounded text-sm text-gray-300 transition-colors flex items-center gap-2"
                  >
                    <Settings size={14} /> 修改库视图结构 (Schema)
                  </button>
                )}
             </div>
             
             {activeTemplate ? (
               <div className="space-y-6">
                 <div>
                   <h3 className="text-[10px] font-bold text-gray-500 uppercase tracking-widest mb-4">
                     特定领域分类渲染级重叠裁决权重阵列 (Painter's Algorithm Weight)
                   </h3>
                   <div className="space-y-2">
                      {(activeTemplate.classes || []).sort((a, b) => b.zIndex - a.zIndex).map((cls) => (
                        <div key={cls.id} className="grid grid-cols-4 gap-4 p-3 bg-[#0d0d0d] border border-white/5 rounded items-center">
                          <div className="col-span-1 flex items-center gap-2">
                             <div className="w-3 h-3 rounded" style={{ backgroundColor: cls.color }}></div>
                             <span className="font-medium text-sm text-gray-300">{cls.name}</span>
                          </div>
                          <div className="col-span-1 font-mono text-xs text-gray-500">优先级 Z-Level: {cls.zIndex}</div>
                          <div className="col-span-2 flex justify-end">
                            <span className="bg-white/5 text-gray-400 text-xs px-2 py-1 rounded border border-white/10">{cls.category || '未分类'}</span>
                          </div>
                        </div>
                      ))}
                      {(activeTemplate.classes || []).length === 0 && (
                        <div className="text-sm text-gray-500 text-center py-8">暂无分类定义</div>
                      )}
                   </div>
                 </div>
               </div>
             ) : (
               <div className="text-sm text-gray-500 text-center py-12">请从左侧选择一个模板或创建新模板</div>
             )}
           </div>
        </div>
      </div>

      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
          <div className="bg-[#111] border border-white/10 rounded-2xl p-6 w-full max-w-2xl max-h-[80vh] overflow-y-auto shadow-2xl">
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-lg font-semibold text-white">{selectedTemplate ? '编辑模板' : '新建模板'}</h2>
              <button onClick={() => setShowModal(false)} className="text-gray-500 hover:text-white transition-colors">
                <X size={18} />
              </button>
            </div>

            <div className="space-y-4 mb-6">
              <div>
                <label className="block text-xs font-medium text-gray-400 uppercase tracking-widest mb-2">模板名称</label>
                <input
                  type="text"
                  value={editName}
                  onChange={(e) => setEditName(e.target.value)}
                  className="w-full bg-[#1a1a1a] border border-white/10 rounded-lg px-4 py-3 text-sm focus:outline-none focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/50 transition-all"
                />
              </div>
              <div>
                <label className="block text-xs font-medium text-gray-400 uppercase tracking-widest mb-2">描述</label>
                <input
                  type="text"
                  value={editDesc}
                  onChange={(e) => setEditDesc(e.target.value)}
                  className="w-full bg-[#1a1a1a] border border-white/10 rounded-lg px-4 py-3 text-sm focus:outline-none focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/50 transition-all"
                />
              </div>
            </div>

            <div className="mb-4">
              <div className="flex justify-between items-center mb-3">
                <h3 className="text-xs font-bold text-gray-500 uppercase tracking-widest">分类定义</h3>
                <button
                  onClick={addClass}
                  className="text-cyan-400 hover:text-cyan-300 text-xs transition-colors flex items-center gap-1"
                >
                  <Plus size={12} /> 添加分类
                </button>
              </div>
              <div className="space-y-2">
                {editClasses.map((cls) => (
                  <div key={cls.id} className="flex items-center gap-3 bg-[#0d0d0d] border border-white/5 rounded-lg p-3">
                    <input
                      type="color"
                      value={cls.color}
                      onChange={(e) => updateClass(cls.id, { color: e.target.value })}
                      className="w-8 h-8 rounded bg-transparent border-0 cursor-pointer"
                    />
                    {editingClassId === cls.id ? (
                      <>
                        <input
                          type="text"
                          value={cls.name}
                          onChange={(e) => updateClass(cls.id, { name: e.target.value })}
                          onBlur={() => setEditingClassId(null)}
                          onKeyDown={(e) => e.key === 'Enter' && setEditingClassId(null)}
                          autoFocus
                          className="flex-1 bg-[#1a1a1a] border border-white/10 rounded px-2 py-1 text-sm text-white"
                        />
                        <input
                          type="number"
                          value={cls.zIndex}
                          onChange={(e) => updateClass(cls.id, { zIndex: parseInt(e.target.value) || 0 })}
                          className="w-20 bg-[#1a1a1a] border border-white/10 rounded px-2 py-1 text-sm text-white font-mono"
                        />
                      </>
                    ) : (
                      <>
                        <span 
                          className="flex-1 text-sm text-gray-300 cursor-pointer"
                          onClick={() => setEditingClassId(cls.id)}
                        >
                          {cls.name}
                        </span>
                        <span className="w-20 text-sm text-gray-500 font-mono text-right">z:{cls.zIndex}</span>
                      </>
                    )}
                    <button onClick={() => removeClass(cls.id)} className="text-gray-500 hover:text-red-400 transition-colors">
                      <Trash2 size={14} />
                    </button>
                  </div>
                ))}
                {editClasses.length === 0 && (
                  <div className="text-sm text-gray-500 text-center py-4">暂无分类，请点击上方按钮添加</div>
                )}
              </div>
            </div>

            <div className="flex justify-end gap-3">
              <button
                onClick={() => setShowModal(false)}
                className="px-4 py-2 rounded-lg text-sm text-gray-400 hover:text-white transition-colors"
              >
                取消
              </button>
              <button
                onClick={handleSave}
                disabled={isSaving || !editName.trim()}
                className={cn(
                  "px-4 py-2 rounded-lg text-sm font-medium flex items-center gap-2 transition-all",
                  isSaving || !editName.trim()
                    ? "bg-cyan-500/50 text-black/70 cursor-not-allowed"
                    : "bg-cyan-500 hover:bg-cyan-400 text-black"
                )}
              >
                {isSaving && <Loader2 size={14} className="animate-spin" />}
                保存
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
