import { DragOutlined, EditOutlined } from '@ant-design/icons';
import { useSortable } from '@dnd-kit/sortable';
import { Tag } from 'antd';
import React, { memo } from 'react';
import type { TagItem } from '../types';

interface SortableTagProps {
  tag: TagItem;
  isActive: boolean;
  isOver: boolean;
  onEdit: (tag: TagItem) => void;
  onDelete: (id: string) => void;
}

export const SortableTag: React.FC<SortableTagProps> = memo(
  ({ tag, isActive, isOver, onEdit, onDelete }) => {
    const { attributes, listeners, setNodeRef } = useSortable({
      id: tag.id,
      disabled: tag.disabled,
    });

    // 计算样式类名
    const className = [
      'sortable-tag',
      tag.disabled && 'disabled',
      isActive && 'active',
      isOver && !tag.disabled && 'over',
    ]
      .filter(Boolean)
      .join(' ');

    // 处理删除
    const handleDelete = (e: React.MouseEvent) => {
      e.preventDefault();
      if (!tag.disabled) {
        onDelete(tag.id);
      }
    };

    // 处理编辑
    const handleEdit = (e: React.MouseEvent) => {
      e.stopPropagation();
      onEdit(tag);
    };

    return (
      <div ref={setNodeRef} className={className}>
        <Tag
          className="custom-tag"
          closable={!tag.disabled}
          onClose={handleDelete}
        >
          <div className="tag-content">
            {!tag.disabled && (
              <span className="drag-handle" {...attributes} {...listeners}>
                <DragOutlined />
              </span>
            )}

            <span className="tag-label">
              {tag.label}
              <span className="sort-badge">{tag.sort}</span>
            </span>

            <EditOutlined className="edit-icon" onClick={handleEdit} />

            {tag.disabled && <span className="disabled-badge">禁用</span>}
          </div>
        </Tag>
      </div>
    );
  },
  // 自定义比较函数，只在必要时重新渲染
  (prevProps, nextProps) => {
    return (
      prevProps.tag.id === nextProps.tag.id &&
      prevProps.tag.label === nextProps.tag.label &&
      prevProps.tag.disabled === nextProps.tag.disabled &&
      prevProps.tag.sort === nextProps.tag.sort &&
      prevProps.isActive === nextProps.isActive &&
      prevProps.isOver === nextProps.isOver
    );
  },
);

SortableTag.displayName = 'SortableTag';
