"use client";

import React, { useState, useRef } from "react";
import { cn } from "@/lib/utils";
import { TableRow, TableCell } from "@/components/ui/table";
import type { TableRowData } from "./enhanced-table";

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

export interface DraggableRowProps {
  /** 行数据 */
  rowData: TableRowData;
  /** 列数组 */
  columns: string[];
  /** 行索引 */
  index: number;
  /** 是否可见 */
  isVisible: boolean;
  /** 是否选中 */
  isSelected: boolean;
  /** 是否启用拖拽 */
  isDraggable: boolean;
  /** 是否正在拖拽 */
  isDragging: boolean;
  /** 是否为拖拽目标 */
  isDragOver: boolean;
  /** 动画持续时间 */
  animationDuration: number;
  /** 点击回调 */
  onClick: () => void;
  /** 拖拽开始回调 */
  onDragStart: (index: number) => void;
  /** 拖拽结束回调 */
  onDragEnd: () => void;
  /** 拖拽进入回调 */
  onDragEnter: (index: number) => void;
  /** 拖拽离开回调 */
  onDragLeave: () => void;
  /** 拖拽悬停回调 */
  onDragOver: (e: React.DragEvent) => void;
  /** 放置回调 */
  onDrop: (e: React.DragEvent) => void;
  /** 删除自定义行回调 */
  onDeleteCustomRow?: (rowId: string) => void;
}

// ============================================================================
// 拖拽行组件
// ============================================================================

export const DraggableRow = React.memo<DraggableRowProps>(({
  rowData,
  columns,
  index,
  isVisible,
  isSelected,
  isDraggable,
  isDragging,
  isDragOver,
  animationDuration,
  onClick,
  onDragStart,
  onDragEnd,
  onDragEnter,
  onDragLeave,
  onDragOver,
  onDrop,
  onDeleteCustomRow
}) => {
  const [isHovered, setIsHovered] = useState(false);
  const dragHandleRef = useRef<HTMLDivElement>(null);

  const handleDragStart = (e: React.DragEvent) => {
    if (!isDraggable) {
      e.preventDefault();
      return;
    }
    
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/plain', rowData.id);
    onDragStart(index);
  };

  const handleClick = (e: React.MouseEvent) => {
    // 如果点击的是拖拽手柄或删除按钮，不触发行点击
    if (
      dragHandleRef.current?.contains(e.target as Node) ||
      (e.target as HTMLElement).closest('.delete-button')
    ) {
      return;
    }
    
    // 如果是自定义行（特别是分隔线），不触发行点击
    if (rowData.isCustomRow) {
      return;
    }
    
    onClick();
  };

  const handleDeleteCustomRow = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (onDeleteCustomRow && rowData.isCustomRow) {
      onDeleteCustomRow(rowData.id);
    }
  };

  // 渲染自定义行内容
  const renderCustomRowContent = () => {
    if (!rowData.isCustomRow) return null;

    switch (rowData.customRowType) {
      case 'empty':
        return (
          <>
            <TableCell className="font-medium text-gray-500 italic">
              <div className="flex items-center gap-2">
                {isDraggable && (
                  <div
                    ref={dragHandleRef}
                    className="cursor-grab active:cursor-grabbing p-1 hover:bg-gray-200 rounded"
                    title="拖拽排序"
                  >
                    <svg className="h-4 w-4 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                      <path d="M10 6a2 2 0 110-4 2 2 0 010 4zM10 12a2 2 0 110-4 2 2 0 010 4zM10 18a2 2 0 110-4 2 2 0 010 4z" />
                    </svg>
                  </div>
                )}
                <span>{rowData.displayText}</span>
                {onDeleteCustomRow && (
                  <button
                    onClick={handleDeleteCustomRow}
                    className="delete-button ml-auto p-1 text-red-400 hover:text-red-600 hover:bg-red-50 rounded"
                    title="删除此行"
                  >
                    <svg className="h-4 w-4" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                    </svg>
                  </button>
                )}
              </div>
            </TableCell>
            {columns.map((column) => (
              <TableCell key={column} className="text-right text-gray-400 italic">
                {column}
              </TableCell>
            ))}
          </>
        );
      
      case 'separator':
        return (
          <TableCell colSpan={columns.length + 1} className="py-2">
            <div className="flex items-center gap-2">
              {isDraggable && (
                <div
                  ref={dragHandleRef}
                  className="cursor-grab active:cursor-grabbing p-1 hover:bg-gray-200 rounded"
                  title="拖拽排序"
                >
                  <svg className="h-4 w-4 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                    <path d="M10 6a2 2 0 110-4 2 2 0 010 4zM10 12a2 2 0 110-4 2 2 0 010 4zM10 18a2 2 0 110-4 2 2 0 010 4z" />
                  </svg>
                </div>
              )}
              <div className="flex-1 border-t border-gray-300"></div>
              <span className="text-sm text-gray-500 px-2">{rowData.displayText}</span>
              <div className="flex-1 border-t border-gray-300"></div>
              {onDeleteCustomRow && (
                <button
                  onClick={handleDeleteCustomRow}
                  className="delete-button p-1 text-red-400 hover:text-red-600 hover:bg-red-50 rounded"
                  title="删除此行"
                >
                  <svg className="h-4 w-4" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                  </svg>
                </button>
              )}
            </div>
          </TableCell>
        );
      
      case 'note':
        return (
          <>
            <TableCell className="font-medium text-blue-600">
              <div className="flex items-center gap-2">
                {isDraggable && (
                  <div
                    ref={dragHandleRef}
                    className="cursor-grab active:cursor-grabbing p-1 hover:bg-gray-200 rounded"
                    title="拖拽排序"
                  >
                    <svg className="h-4 w-4 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                      <path d="M10 6a2 2 0 110-4 2 2 0 010 4zM10 12a2 2 0 110-4 2 2 0 010 4zM10 18a2 2 0 110-4 2 2 0 010 4z" />
                    </svg>
                  </div>
                )}
                <svg className="h-4 w-4 text-blue-500" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
                </svg>
                <span>{rowData.displayText}</span>
                {onDeleteCustomRow && (
                  <button
                    onClick={handleDeleteCustomRow}
                    className="delete-button ml-auto p-1 text-red-400 hover:text-red-600 hover:bg-red-50 rounded"
                    title="删除此行"
                  >
                    <svg className="h-4 w-4" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                    </svg>
                  </button>
                )}
              </div>
            </TableCell>
            {columns.map((column) => (
              <TableCell key={column} className="text-right text-gray-400">
                -
              </TableCell>
            ))}
          </>
        );
      
      default:
        return null;
    }
  };

  // 渲染普通数据行内容
  const renderDataRowContent = () => (
    <>
      <TableCell className="font-medium">
        <div className="flex items-center gap-2">
          {isDraggable && (
            <div
              ref={dragHandleRef}
              className="cursor-grab active:cursor-grabbing p-1 hover:bg-gray-200 rounded opacity-0 group-hover:opacity-100 transition-opacity"
              title="拖拽排序"
            >
              <svg className="h-4 w-4 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                <path d="M10 6a2 2 0 110-4 2 2 0 010 4zM10 12a2 2 0 110-4 2 2 0 010 4zM10 18a2 2 0 110-4 2 2 0 010 4z" />
              </svg>
            </div>
          )}
          <span>{rowData.displayText}</span>
        </div>
      </TableCell>
      {columns.map((column) => (
        <TableCell key={column} className="text-right">
          {rowData.values[column] ?? "-"}
        </TableCell>
      ))}
    </>
  );

  return (
    <TableRow
      draggable={isDraggable}
      isVisible={isVisible}
      animationDuration={animationDuration}
      className={cn(
        "group transition-all duration-200",
        isSelected && "bg-indigo-50 border-indigo-200",
        isDragging && "opacity-50 scale-95",
        isDragOver && "bg-blue-50 border-blue-300 border-t-2",
        isHovered && !isDragging && "bg-muted/70",
        rowData.isCustomRow && "bg-gray-50/50",
        !rowData.isCustomRow && "cursor-pointer hover:bg-muted/70",
        rowData.isCustomRow && "cursor-default"
      )}
      onClick={handleClick}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      onDragStart={handleDragStart}
      onDragEnd={onDragEnd}
      onDragEnter={() => onDragEnter(index)}
      onDragLeave={onDragLeave}
      onDragOver={onDragOver}
      onDrop={onDrop}
    >
      {rowData.isCustomRow ? renderCustomRowContent() : renderDataRowContent()}
    </TableRow>
  );
});

DraggableRow.displayName = "DraggableRow";