/**
 * 钉钉风格流程设计器
 * 垂直布局，卡片式节点
 */

'use client';

import React, { useState, useCallback, useEffect } from 'react';
import {
  Plus,
  User,
  Users,
  UserCheck,
  Mail,
  MessageSquare,
  GitBranch,
  GitMerge,
  Database,
  RefreshCw,
  Search,
  Link2,
  ChevronRight,
  X,
  Trash2,
  GripVertical,
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  ProcessModel,
  ProcessNode,
  ProcessNodeType,
  ProcessNodeConfig,
  generateNodeId,
  generateEdgeId,
  createDefaultProcessModel,
} from './types';
import { useTranslation } from '@/hooks/useTranslation';

// ============================================
// 类型定义
// ============================================

interface NodeTypeOption {
  type: ProcessNodeType;
  label: string;
  icon: React.ElementType;
  color: string;
  category: 'human' | 'message' | 'branch' | 'connector' | 'data';
  description?: string;
}

const getNodeTypeOptions = (t: any): NodeTypeOption[] => [
  // 人工节点
  { type: 'USER_TASK', label: t.approvals.dingDesigner.defaultNodeNames.approver, icon: UserCheck, color: '#1677ff', category: 'human' },
  { type: 'CC', label: t.approvals.dingDesigner.defaultNodeNames.cc, icon: Users, color: '#1677ff', category: 'human' },
  // 分支节点
  { type: 'EXCLUSIVE_GATEWAY', label: t.approvals.dingDesigner.defaultNodeNames.conditionalBranch, icon: GitBranch, color: '#fa8c16', category: 'branch' },
  { type: 'PARALLEL_GATEWAY', label: t.approvals.dingDesigner.defaultNodeNames.parallelBranch, icon: GitMerge, color: '#fa8c16', category: 'branch' },
];

const getNodeCategories = (t: any) => [
  { key: 'human', label: t.approvals.dingDesigner.nodeCategories.human },
  { key: 'branch', label: t.approvals.dingDesigner.nodeCategories.branch },
];

// ============================================
// 辅助组件
// ============================================

// 添加节点按钮和弹出菜单
interface AddNodeButtonProps {
  onAdd: (type: ProcessNodeType) => void;
}

function AddNodeButton({ onAdd }: AddNodeButtonProps) {
  const [isOpen, setIsOpen] = useState(false);
  const { t } = useTranslation();
  const nodeTypeOptions = getNodeTypeOptions(t);
  const nodeCategories = getNodeCategories(t);

  const handleAdd = (type: ProcessNodeType) => {
    onAdd(type);
    setIsOpen(false);
  };

  return (
    <div className="relative flex flex-col items-center">
      {/* 连接线 */}
      <div className="w-px h-8 bg-gray-300" />
      
      {/* 添加按钮 */}
      <button
        onClick={() => setIsOpen(!isOpen)}
        className={`
          w-7 h-7 rounded-full flex items-center justify-center
          transition-all duration-200 z-10
          ${isOpen 
            ? 'bg-blue-500 text-white shadow-lg scale-110' 
            : 'bg-blue-500 text-white hover:bg-blue-600 hover:shadow-md'
          }
        `}
      >
        <Plus className={`w-4 h-4 transition-transform ${isOpen ? 'rotate-45' : ''}`} />
      </button>

      {/* 连接线 */}
      <div className="w-px h-8 bg-gray-300" />
      
      {/* 箭头 */}
      <div className="w-0 h-0 border-l-4 border-r-4 border-t-6 border-l-transparent border-r-transparent border-t-gray-300" />

      {/* 弹出菜单 */}
      <AnimatePresence>
        {isOpen && (
          <>
            {/* 遮罩 */}
            <div 
              className="fixed inset-0 z-20" 
              onClick={() => setIsOpen(false)} 
            />
            
            {/* 菜单 */}
            <motion.div
              initial={{ opacity: 0, scale: 0.9, y: -10 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.9, y: -10 }}
              transition={{ duration: 0.15 }}
              className="absolute left-full ml-4 top-1/2 -translate-y-1/2 z-30 w-80 bg-gray-900 rounded-xl shadow-2xl overflow-hidden"
            >
              <div className="p-4 space-y-4">
                {nodeCategories.map((category) => {
                  const options = nodeTypeOptions.filter(
                    (opt) => opt.category === category.key
                  );
                  if (options.length === 0) return null;

                  return (
                    <div key={category.key}>
                      <div className="text-xs text-gray-400 mb-2">{category.label}</div>
                      <div className="grid grid-cols-2 gap-2">
                        {options.map((option) => (
                          <button
                            key={option.type}
                            onClick={() => handleAdd(option.type)}
                            className="flex items-center gap-3 px-3 py-2.5 rounded-lg bg-gray-800 hover:bg-gray-700 transition-colors text-left"
                          >
                            <div
                              className="w-8 h-8 rounded-lg flex items-center justify-center"
                              style={{ backgroundColor: option.color }}
                            >
                              <option.icon className="w-4 h-4 text-white" />
                            </div>
                            <span className="text-sm text-white">{option.label}</span>
                          </button>
                        ))}
                      </div>
                    </div>
                  );
                })}
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </div>
  );
}

// 发起节点
function StartNode() {
  const { t } = useTranslation();
  return (
    <div className="flex flex-col items-center">
      <div className="flex items-center gap-2 px-5 py-2.5 bg-gray-700 rounded-full text-white">
        <User className="w-4 h-4" />
        <span className="text-sm font-medium">{t.approvals.dingDesigner.defaultNodeNames.start}</span>
        <ChevronRight className="w-4 h-4" />
      </div>
    </div>
  );
}

// 结束节点
function EndNode() {
  const { t } = useTranslation();
  return (
    <div className="flex flex-col items-center">
      <div className="px-8 py-2 bg-gray-200 rounded-full text-gray-600 text-sm font-medium">
        {t.approvals.dingDesigner.defaultNodeNames.end}
      </div>
    </div>
  );
}

// 审批节点卡片
interface ApprovalNodeCardProps {
  node: ProcessNode;
  isSelected: boolean;
  onSelect: () => void;
  onDelete: () => void;
  onUpdate: (updates: Partial<ProcessNode>) => void;
}

function ApprovalNodeCard({
  node,
  isSelected,
  onSelect,
  onDelete,
  onUpdate,
}: ApprovalNodeCardProps) {
  const { t } = useTranslation();
  
  const getApproverLabel = () => {
    const type = node.config?.approverType;
    if (!type) return t.approvals.dingDesigner.pleaseSetApprover;
    
    const config = t.approvals?.approverTypesConfig?.[type];
    return config?.label || t.approvals.dingDesigner.pleaseSetApprover;
  };

  return (
    <div
      onClick={onSelect}
      className={`
        relative w-72 bg-white rounded-xl shadow-sm border-2 cursor-pointer
        transition-all duration-200 hover:shadow-md
        ${isSelected ? 'border-blue-500 shadow-md' : 'border-gray-200'}
      `}
    >
      {/* 顶部条 */}
      <div className="h-1 bg-blue-500 rounded-t-xl" />
      
      {/* 内容 */}
      <div className="p-4">
        <div className="flex items-start gap-3">
          {/* 图标 */}
          <div className="w-10 h-10 rounded-lg bg-blue-500 flex items-center justify-center flex-shrink-0">
            <UserCheck className="w-5 h-5 text-white" />
          </div>
          
          {/* 信息 */}
          <div className="flex-1 min-w-0">
            <div className="text-base font-medium text-gray-900 truncate">
              {node.name}
            </div>
            <div className="text-sm text-gray-500 mt-0.5 flex items-center gap-1">
              {getApproverLabel()}
              <ChevronRight className="w-4 h-4 text-gray-400" />
            </div>
          </div>
        </div>
      </div>

      {/* 删除按钮 */}
      {isSelected && (
        <button
          onClick={(e) => {
            e.stopPropagation();
            onDelete();
          }}
          className="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center hover:bg-red-600 shadow-md"
        >
          <X className="w-3.5 h-3.5" />
        </button>
      )}
    </div>
  );
}

// 抄送节点卡片
interface CCNodeCardProps {
  node: ProcessNode;
  isSelected: boolean;
  onSelect: () => void;
  onDelete: () => void;
  onUpdate: (updates: Partial<ProcessNode>) => void;
}

function CCNodeCard({
  node,
  isSelected,
  onSelect,
  onDelete,
  onUpdate,
}: CCNodeCardProps) {
  return (
    <div
      onClick={onSelect}
      className={`
        relative w-72 bg-white rounded-xl shadow-sm border-2 cursor-pointer
        transition-all duration-200 hover:shadow-md
        ${isSelected ? 'border-purple-500 shadow-md' : 'border-gray-200'}
      `}
    >
      {/* 顶部条 */}
      <div className="h-1 bg-purple-500 rounded-t-xl" />
      
      {/* 内容 */}
      <div className="p-4">
        <div className="flex items-start gap-3">
          {/* 图标 */}
          <div className="w-10 h-10 rounded-lg bg-purple-500 flex items-center justify-center flex-shrink-0">
            <Users className="w-5 h-5 text-white" />
          </div>
          
          {/* 信息 */}
          <div className="flex-1 min-w-0">
            <div className="text-base font-medium text-gray-900 truncate">
              {node.name}
            </div>
            <div className="text-sm text-gray-500 mt-0.5 flex items-center gap-1">
              请设置抄送人
              <ChevronRight className="w-4 h-4 text-gray-400" />
            </div>
          </div>
        </div>
      </div>

      {/* 删除按钮 */}
      {isSelected && (
        <button
          onClick={(e) => {
            e.stopPropagation();
            onDelete();
          }}
          className="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center hover:bg-red-600 shadow-md"
        >
          <X className="w-3.5 h-3.5" />
        </button>
      )}
    </div>
  );
}

// 条件分支节点
interface BranchNodeProps {
  node: ProcessNode;
  isSelected: boolean;
  onSelect: () => void;
  onDelete: () => void;
  branches: ProcessNode[][];
  onAddBranch: () => void;
}

function BranchNode({
  node,
  isSelected,
  onSelect,
  onDelete,
  branches,
  onAddBranch,
}: BranchNodeProps) {
  const { t } = useTranslation();
  const isParallel = node.type === 'PARALLEL_GATEWAY';
  
  return (
    <div className="flex flex-col items-center">
      {/* 分支标题 */}
      <div
        onClick={onSelect}
        className={`
          relative flex items-center gap-2 px-4 py-2 rounded-lg cursor-pointer
          transition-all duration-200
          ${isSelected 
            ? 'bg-orange-100 border-2 border-orange-500' 
            : 'bg-orange-50 border-2 border-orange-200 hover:border-orange-300'
          }
        `}
      >
        {isParallel ? (
          <GitMerge className="w-4 h-4 text-orange-500" />
        ) : (
          <GitBranch className="w-4 h-4 text-orange-500" />
        )}
        <span className="text-sm font-medium text-orange-700">
          {isParallel ? t.approvals.dingDesigner.defaultNodeNames.parallelBranch : t.approvals.dingDesigner.defaultNodeNames.conditionalBranch}
        </span>
        <button
          onClick={(e) => {
            e.stopPropagation();
            onAddBranch();
          }}
          className="ml-2 text-orange-500 hover:text-orange-600"
        >
          <Plus className="w-4 h-4" />
        </button>
        
        {isSelected && (
          <button
            onClick={(e) => {
              e.stopPropagation();
              onDelete();
            }}
            className="absolute -top-2 -right-2 w-5 h-5 bg-red-500 text-white rounded-full flex items-center justify-center hover:bg-red-600"
          >
            <X className="w-3 h-3" />
          </button>
        )}
      </div>
    </div>
  );
}

// ============================================
// 主组件
// ============================================

interface DingStyleDesignerProps {
  initialModel?: ProcessModel;
  onChange?: (model: ProcessModel) => void;
}

export function DingStyleDesigner({ initialModel, onChange }: DingStyleDesignerProps) {
  const { t } = useTranslation();
  const [nodes, setNodes] = useState<ProcessNode[]>([]);
  const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);

  // 初始化
  useEffect(() => {
    if (initialModel && initialModel.nodes.length > 0) {
      // 过滤掉 START 和 END 节点（我们会自动显示）
      const workNodes = initialModel.nodes.filter(
        (n) => n.type !== 'START' && n.type !== 'END'
      );
      setNodes(workNodes);
    }
  }, [initialModel]);

  // 通知变化
  useEffect(() => {
    if (onChange) {
      const startNode: ProcessNode = {
        id: 'start',
        type: 'START',
        name: t.approvals.dingDesigner.defaultNodeNames.start,
        position: { x: 0, y: 0 },
        config: {},
      };
      const endNode: ProcessNode = {
        id: 'end',
        type: 'END',
        name: t.approvals.dingDesigner.defaultNodeNames.end,
        position: { x: 0, y: 0 },
        config: {},
      };
      
      // 构建完整模型
      const allNodes = [startNode, ...nodes, endNode];
      const edges = allNodes.slice(0, -1).map((node, index) => ({
        id: generateEdgeId(),
        source: node.id,
        target: allNodes[index + 1].id,
      }));
      
      onChange({ nodes: allNodes, edges });
    }
  }, [nodes, onChange]);

  // 在指定位置添加节点
  const handleAddNode = useCallback((afterIndex: number, type: ProcessNodeType) => {
    const newNode: ProcessNode = {
      id: generateNodeId(),
      type,
      name: type === 'USER_TASK' ? t.approvals.dingDesigner.defaultNodeNames.approver : 
            type === 'CC' ? t.approvals.dingDesigner.defaultNodeNames.cc :
            type === 'EXCLUSIVE_GATEWAY' ? t.approvals.dingDesigner.defaultNodeNames.conditionalBranch :
            type === 'PARALLEL_GATEWAY' ? t.approvals.dingDesigner.defaultNodeNames.parallelBranch : t.approvals.dingDesigner.defaultNodeNames.node,
      position: { x: 0, y: 0 },
      config: type === 'USER_TASK' ? { approverType: 'INITIATOR_MANAGER', approvalMode: 'SINGLE' } : {},
    };
    
    setNodes((prev) => {
      const newNodes = [...prev];
      newNodes.splice(afterIndex, 0, newNode);
      return newNodes;
    });
    setSelectedNodeId(newNode.id);
  }, []);

  // 删除节点
  const handleDeleteNode = useCallback((nodeId: string) => {
    setNodes((prev) => prev.filter((n) => n.id !== nodeId));
    setSelectedNodeId(null);
  }, []);

  // 更新节点
  const handleUpdateNode = useCallback((nodeId: string, updates: Partial<ProcessNode>) => {
    setNodes((prev) =>
      prev.map((n) => (n.id === nodeId ? { ...n, ...updates } : n))
    );
  }, []);

  // 选择节点
  const handleSelectNode = useCallback((nodeId: string | null) => {
    setSelectedNodeId(nodeId);
  }, []);

  // 渲染节点
  const renderNode = (node: ProcessNode, index: number) => {
    const isSelected = selectedNodeId === node.id;

    switch (node.type) {
      case 'USER_TASK':
        return (
          <ApprovalNodeCard
            key={node.id}
            node={node}
            isSelected={isSelected}
            onSelect={() => handleSelectNode(node.id)}
            onDelete={() => handleDeleteNode(node.id)}
            onUpdate={(updates) => handleUpdateNode(node.id, updates)}
          />
        );
      case 'CC':
        return (
          <CCNodeCard
            key={node.id}
            node={node}
            isSelected={isSelected}
            onSelect={() => handleSelectNode(node.id)}
            onDelete={() => handleDeleteNode(node.id)}
            onUpdate={(updates) => handleUpdateNode(node.id, updates)}
          />
        );
      case 'EXCLUSIVE_GATEWAY':
      case 'PARALLEL_GATEWAY':
        return (
          <BranchNode
            key={node.id}
            node={node}
            isSelected={isSelected}
            onSelect={() => handleSelectNode(node.id)}
            onDelete={() => handleDeleteNode(node.id)}
            branches={[]}
            onAddBranch={() => {}}
          />
        );
      default:
        return null;
    }
  };

  return (
    <div className="h-full bg-[#f7f8fa] overflow-auto">
      {/* 点状背景 */}
      <div 
        className="min-h-full py-12"
        style={{
          backgroundImage: 'radial-gradient(circle, #d1d5db 1px, transparent 1px)',
          backgroundSize: '20px 20px',
        }}
        onClick={() => handleSelectNode(null)}
      >
        <div className="flex flex-col items-center">
          {/* 发起节点 */}
          <StartNode />
          
          {/* 添加第一个节点的按钮 */}
          <AddNodeButton onAdd={(type) => handleAddNode(0, type)} />

          {/* 工作节点 */}
          {nodes.map((node, index) => (
            <React.Fragment key={node.id}>
              {renderNode(node, index)}
              <AddNodeButton onAdd={(type) => handleAddNode(index + 1, type)} />
            </React.Fragment>
          ))}

          {/* 结束节点 */}
          <EndNode />
        </div>
      </div>
    </div>
  );
}

export default DingStyleDesigner;
