import React, { useState, useEffect } from 'react';
import { Settings, Database, Trash2, Edit3, Plus, Loader2, X, GripVertical, Import } 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';

// HSL to Hex color generator
function hslToHex(h: number, s: number, l: number): string {
  l /= 100;
  const a = s * Math.min(l, 1 - l) / 100;
  const f = (n: number) => {
    const k = (n + h / 30) % 12;
    const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
    return Math.round(255 * color).toString(16).padStart(2, '0');
  };
  return `#${f(0)}${f(8)}${f(4)}`;
}

function generateColor(index: number, total: number): string {
  const hue = (index * 360 / Math.max(total, 1)) % 360;
  return hslToHex(hue, 75, 55);
}

const LAPAROSCOPIC_COLORS = [
  [134, 124, 118], [0, 157, 142], [245, 161, 0], [255, 172, 159], [146, 175, 236], [155, 62, 0],
  [255, 91, 0], [255, 234, 0], [85, 111, 181], [155, 132, 0], [181, 227, 14], [72, 0, 255],
  [255, 0, 255], [29, 32, 136], [240, 16, 116], [160, 15, 95], [0, 155, 33], [0, 160, 233],
  [52, 184, 178], [66, 115, 82], [90, 120, 41], [255, 0, 0], [117, 0, 0], [167, 24, 233],
  [42, 8, 66], [112, 113, 150], [0, 255, 0], [255, 255, 255], [0, 255, 255], [181, 85, 105],
  [113, 102, 140], [202, 202, 200], [197, 83, 181], [136, 162, 196], [138, 251, 213],
];

const LAPAROSCOPIC_NAMES = [
  '针', '线', '肿瘤', '血管阻断夹', '棉球', '双极电凝',
  '肝脏', '胆囊', '分离钳', '脂肪', '止血海绵', '肝总管',
  '吸引器', '剪刀', '超声刀', '止血纱布', '胆总管', '生物夹',
  '无损伤钳', '钳夹', '喷洒', '胆囊管', '动脉', '电凝',
  '静脉', '标本袋', '引流管', '纱布', '金属钛夹', '韧带',
  '肝蒂', '推结器', '乳胶管-血管阻断', '吻合器', '术中超声',
];

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 [showImport, setShowImport] = useState(false);
  const [importText, setImportText] = useState('');

  const [editName, setEditName] = useState('');
  const [editDesc, setEditDesc] = useState('');
  const [editClasses, setEditClasses] = useState<TemplateClass[]>([]);
  const [editingClassId, setEditingClassId] = useState<string | null>(null);
  const [dragOverIndex, setDragOverIndex] = useState<number | 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 {
      const basePayload = {
        name: editName.trim(),
        description: editDesc.trim() || undefined,
        classes: editClasses,
        rules: [],
        color: selectedTemplate ? (selectedTemplate as any).color || '#06b6d4' : '#06b6d4',
        z_index: selectedTemplate ? (selectedTemplate as any).z_index ?? 0 : 0,
      };
      if (selectedTemplate) {
        const updated = await updateTemplate(selectedTemplate.id, basePayload);
        updateTemplateStore(updated);
      } else {
        const created = await createTemplate(basePayload);
        addTemplate(created);
      }
      setShowModal(false);
    } catch (err) {
      console.error('Failed to save template:', err);
      alert('保存失败，请查看控制台');
    } 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: generateColor(editClasses.length, Math.max(editClasses.length + 1, 8)),
      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 reorderClasses = (fromIndex: number, toIndex: number) => {
    if (fromIndex === toIndex) return;
    const items = [...editClasses];
    const [moved] = items.splice(fromIndex, 1);
    items.splice(toIndex, 0, moved);
    // Recalculate z-index based on new order (top = highest)
    const recalculated = items.map((c, i) => ({ ...c, zIndex: (items.length - i) * 10 }));
    setEditClasses(recalculated);
  };

  const handleImport = () => {
    try {
      const data = JSON.parse(importText);
      let colors: number[][] = [];
      let names: string[] = [];

      if (Array.isArray(data) && data.length === 2 && Array.isArray(data[0]) && Array.isArray(data[1])) {
        colors = data[0];
        names = data[1];
      } else if (Array.isArray(data.colors) && Array.isArray(data.names)) {
        colors = data.colors;
        names = data.names;
      } else {
        alert('格式错误：请提供 [[colors...], [names...]] 或 {colors, names}');
        return;
      }

      const imported: TemplateClass[] = names.map((name: string, i: number) => {
        const rgb = colors[i] || [100, 100, 100];
        const hex = `#${rgb[0].toString(16).padStart(2, '0')}${rgb[1].toString(16).padStart(2, '0')}${rgb[2].toString(16).padStart(2, '0')}`;
        return {
          id: `cls-import-${Date.now()}-${i}`,
          name,
          color: hex,
          zIndex: (names.length - i) * 10,
          category: '批量导入',
        };
      });

      setEditClasses([...editClasses, ...imported]);
      setShowImport(false);
      setImportText('');
    } catch (e) {
      alert('JSON 解析失败');
    }
  };

  const loadLaparoscopic = () => {
    const imported: TemplateClass[] = LAPAROSCOPIC_NAMES.map((name, i) => {
      const rgb = LAPAROSCOPIC_COLORS[i];
      const hex = `#${rgb[0].toString(16).padStart(2, '0')}${rgb[1].toString(16).padStart(2, '0')}${rgb[2].toString(16).padStart(2, '0')}`;
      return {
        id: `cls-lap-${Date.now()}-${i}`,
        name,
        color: hex,
        zIndex: (LAPAROSCOPIC_NAMES.length - i) * 10,
        category: '腹腔镜胆囊切除术',
      };
    });
    setEditClasses(imported);
    setShowImport(false);
  };

  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">分类定义 ({editClasses.length} 个)</h3>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => setShowImport(true)}
                    className="text-gray-400 hover:text-white text-xs transition-colors flex items-center gap-1 bg-white/5 px-2 py-1 rounded"
                  >
                    <Import size={12} /> 批量导入
                  </button>
                  <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>
              <div className="space-y-2">
                {editClasses.map((cls, idx) => (
                  <div
                    key={cls.id}
                    draggable
                    onDragStart={(e) => {
                      e.dataTransfer.setData('text/plain', String(idx));
                      e.dataTransfer.effectAllowed = 'move';
                    }}
                    onDragOver={(e) => {
                      e.preventDefault();
                      e.dataTransfer.dropEffect = 'move';
                      setDragOverIndex(idx);
                    }}
                    onDragLeave={() => setDragOverIndex(null)}
                    onDrop={(e) => {
                      e.preventDefault();
                      const fromIndex = parseInt(e.dataTransfer.getData('text/plain'), 10);
                      reorderClasses(fromIndex, idx);
                      setDragOverIndex(null);
                    }}
                    onDragEnd={() => setDragOverIndex(null)}
                    className={cn(
                      "flex items-center gap-2 bg-[#0d0d0d] border rounded-lg p-2 transition-all",
                      dragOverIndex === idx ? "border-cyan-500/50 bg-cyan-500/5" : "border-white/5"
                    )}
                  >
                    <div className="text-gray-600 cursor-grab active:cursor-grabbing shrink-0">
                      <GripVertical size={14} />
                    </div>
                    <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 shrink-0"
                    />
                    {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="text"
                          value={cls.category || ''}
                          onChange={(e) => updateClass(cls.id, { category: e.target.value })}
                          placeholder="类别"
                          className="w-24 bg-[#1a1a1a] border border-white/10 rounded px-2 py-1 text-sm text-white"
                        />
                      </>
                    ) : (
                      <>
                        <span
                          className="flex-1 text-sm text-gray-300 cursor-pointer"
                          onClick={() => setEditingClassId(cls.id)}
                        >
                          {cls.name}
                        </span>
                        <span className="w-16 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>
      )}

      {showImport && (
        <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-lg shadow-2xl">
            <h2 className="text-lg font-semibold text-white mb-4">批量导入分类</h2>
            <p className="text-xs text-gray-500 mb-2">支持格式: JSON 数组 [[colors], [names]] 或 {'{'}&quot;colors&quot;: [...], &quot;names&quot;: [...]{'}'}</p>
            <textarea
              value={importText}
              onChange={(e) => setImportText(e.target.value)}
              placeholder='[[[255,0,0], [0,255,0]], ["分类A", "分类B"]]'
              className="w-full h-32 bg-[#1a1a1a] border border-white/10 rounded-lg px-3 py-2 text-xs text-gray-300 font-mono focus:outline-none focus:border-cyan-500/50 resize-none"
            />
            <div className="flex justify-between items-center mt-4">
              <button
                onClick={loadLaparoscopic}
                className="text-xs text-cyan-400 hover:text-cyan-300 transition-colors"
              >
                📋 载入腹腔镜胆囊切除术模板
              </button>
              <div className="flex gap-3">
                <button
                  onClick={() => { setShowImport(false); setImportText(''); }}
                  className="px-4 py-2 rounded-lg text-sm text-gray-400 hover:text-white transition-colors"
                >
                  取消
                </button>
                <button
                  onClick={handleImport}
                  className="px-4 py-2 rounded-lg text-sm font-medium bg-cyan-500 hover:bg-cyan-400 text-black transition-all"
                >
                  导入
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
