/**
 * 流程预览组件 - 只读展示流程图
 */

'use client';

import React, { useMemo } from 'react';
import ReactFlow, {
  Node,
  Edge,
  Background,
  Controls,
  MiniMap,
  MarkerType,
  NodeTypes,
  Position,
  Handle,
} from 'reactflow';
import 'reactflow/dist/style.css';
import {
  Play,
  Square,
  UserCheck,
  Send,
  GitBranch,
  GitMerge,
} from 'lucide-react';
import { ProcessModel, ProcessNode as ProcessNodeType, PROCESS_NODE_TYPES } from './types';
import { useTranslation } from '@/hooks/useTranslation';

// 自定义节点组件
interface CustomNodeData {
  label: string;
  type: string;
  description?: string;
}

function StartNodePreview({ data }: { data: CustomNodeData }) {
  return (
    <div className="relative">
      <div className="w-12 h-12 rounded-full bg-green-500 flex items-center justify-center shadow-md">
        <Play className="w-5 h-5 text-white fill-white" />
      </div>
      <Handle type="source" position={Position.Bottom} className="w-2 h-2 bg-gray-400" />
    </div>
  );
}

function EndNodePreview({ data }: { data: CustomNodeData }) {
  return (
    <div className="relative">
      <Handle type="target" position={Position.Top} className="w-2 h-2 bg-gray-400" />
      <div className="w-12 h-12 rounded-full bg-red-500 flex items-center justify-center shadow-md">
        <Square className="w-4 h-4 text-white fill-white" />
      </div>
    </div>
  );
}

function UserTaskNodePreview({ data }: { data: CustomNodeData }) {
  return (
    <div className="relative">
      <Handle type="target" position={Position.Top} className="w-2 h-2 bg-gray-400" />
      <div className="min-w-[120px] px-4 py-3 rounded-lg bg-white border-2 border-blue-300 shadow-md">
        <div className="flex items-center gap-2">
          <div className="w-8 h-8 rounded-md bg-blue-500 flex items-center justify-center">
            <UserCheck className="w-4 h-4 text-white" />
          </div>
          <div className="flex-1 min-w-0">
            <div className="text-sm font-medium text-gray-800 truncate">
              {data.label}
            </div>
            {data.description && (
              <div className="text-xs text-gray-500 truncate">{data.description}</div>
            )}
          </div>
        </div>
      </div>
      <Handle type="source" position={Position.Bottom} className="w-2 h-2 bg-gray-400" />
    </div>
  );
}

function CCNodePreview({ data }: { data: CustomNodeData }) {
  return (
    <div className="relative">
      <Handle type="target" position={Position.Top} className="w-2 h-2 bg-gray-400" />
      <div className="min-w-[120px] px-4 py-3 rounded-lg bg-white border-2 border-purple-300 shadow-md">
        <div className="flex items-center gap-2">
          <div className="w-8 h-8 rounded-md bg-purple-500 flex items-center justify-center">
            <Send className="w-4 h-4 text-white" />
          </div>
          <div className="flex-1 min-w-0">
            <div className="text-sm font-medium text-gray-800 truncate">
              {data.label}
            </div>
            <div className="text-xs text-gray-500">抄送</div>
          </div>
        </div>
      </div>
      <Handle type="source" position={Position.Bottom} className="w-2 h-2 bg-gray-400" />
    </div>
  );
}

function ExclusiveGatewayNodePreview({ data }: { data: CustomNodeData }) {
  return (
    <div className="relative">
      <Handle type="target" position={Position.Top} className="w-2 h-2 bg-gray-400" />
      <div className="w-12 h-12 rounded-lg transform rotate-45 bg-amber-500 flex items-center justify-center shadow-md">
        <GitBranch className="w-5 h-5 text-white transform -rotate-45" />
      </div>
      <Handle type="source" position={Position.Bottom} className="w-2 h-2 bg-gray-400" />
    </div>
  );
}

function ParallelGatewayNodePreview({ data }: { data: CustomNodeData }) {
  return (
    <div className="relative">
      <Handle type="target" position={Position.Top} className="w-2 h-2 bg-gray-400" />
      <div className="w-12 h-12 rounded-lg transform rotate-45 bg-cyan-500 flex items-center justify-center shadow-md">
        <GitMerge className="w-5 h-5 text-white transform -rotate-45" />
      </div>
      <Handle type="source" position={Position.Bottom} className="w-2 h-2 bg-gray-400" />
    </div>
  );
}

// 节点类型映射
const nodeTypes: NodeTypes = {
  START: StartNodePreview,
  END: EndNodePreview,
  USER_TASK: UserTaskNodePreview,
  CC: CCNodePreview,
  EXCLUSIVE_GATEWAY: ExclusiveGatewayNodePreview,
  PARALLEL_GATEWAY: ParallelGatewayNodePreview,
};

interface ProcessPreviewProps {
  model: ProcessModel;
  className?: string;
  height?: number | string;
  showControls?: boolean;
  showMiniMap?: boolean;
}

export function ProcessPreview({
  model,
  className = '',
  height = 300,
  showControls = true,
  showMiniMap = false,
}: ProcessPreviewProps) {
  const { t } = useTranslation();

  // 转换节点数据为 React Flow 格式
  const nodes: Node[] = useMemo(() => {
    return model.nodes.map((node) => ({
      id: node.id,
      type: node.type,
      position: node.position,
      data: {
        label: node.name,
        type: node.type,
        description: node.config?.approverType
          ? getApproverTypeLabel(node.config.approverType, t)
          : undefined,
      },
      draggable: false,
      selectable: false,
    }));
  }, [model.nodes, t]);

  // 转换连线数据为 React Flow 格式
  const edges: Edge[] = useMemo(() => {
    return model.edges.map((edge) => ({
      id: edge.id,
      source: edge.source,
      target: edge.target,
      label: edge.label,
      type: 'smoothstep',
      animated: false,
      markerEnd: {
        type: MarkerType.ArrowClosed,
        width: 15,
        height: 15,
        color: '#94a3b8',
      },
      style: {
        stroke: '#94a3b8',
        strokeWidth: 2,
      },
    }));
  }, [model.edges]);

  if (model.nodes.length === 0) {
    return (
      <div
        className={`flex items-center justify-center bg-gray-50 text-gray-400 ${className}`}
        style={{ height }}
      >
        <p className="text-sm">暂无流程节点</p>
      </div>
    );
  }

  return (
    <div className={className} style={{ height }}>
      <ReactFlow
        nodes={nodes}
        edges={edges}
        nodeTypes={nodeTypes}
        fitView
        nodesDraggable={false}
        nodesConnectable={false}
        elementsSelectable={false}
        panOnDrag={true}
        zoomOnScroll={true}
        defaultViewport={{ x: 0, y: 0, zoom: 0.8 }}
      >
        <Background gap={20} size={1} color="#e5e7eb" />
        {showControls && <Controls showInteractive={false} />}
        {showMiniMap && (
          <MiniMap
            nodeColor={(node) => {
              const config = PROCESS_NODE_TYPES.find(
                (c) => c.type === node.type
              );
              return config?.color || '#94a3b8';
            }}
            maskColor="rgb(240, 240, 240, 0.8)"
          />
        )}
      </ReactFlow>
    </div>
  );
}

// 辅助函数：获取审批人类型标签
function getApproverTypeLabel(approverType: string, t: any): string {
  const config = t.approvals?.approverTypesConfig?.[approverType];
  if (config?.label) {
    return config.label;
  }
  // Fallback to type name
  return approverType;
}

export default ProcessPreview;
