"use client";

import React, { useState } from "react";
import { cn } from "@/lib/utils";
import type { TableRowConfig } from "./row-settings";

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

export interface SortableRowItemProps {
  /** 行ID */
  rowId: string;
  /** 显示文本 */
  displayText: string;
  /** 行配置 */
  config: TableRowConfig;
  /** 行索引 */
  index: number;
  /** 是否正在拖拽 */
  isDragging: boolean;
  /** 是否为拖拽目标 */
  isDragOver: boolean;
  /** 可见性变更回调 */
  onVisibilityChange: (rowId: string, visible: boolean) => 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;
  /** 是否启用拖拽排序 */
  enableDragging?: boolean;
}

// ============================================================================
// 可排序行项目组件
// ============================================================================

export function SortableRowItem({
  rowId,
  displayText,
  config,
  index,
  isDragging,
  isDragOver,
  onVisibilityChange,
  onDragStart,
  onDragEnd,
  onDragEnter,
  onDragLeave,
  onDragOver,
  onDrop,
  onDeleteCustomRow,
  enableDragging = true
}: SortableRowItemProps) {
  const [isHovered, setIsHovered] = useState(false);

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

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

  const getRowTypeIcon = () => {
    if (!config.isCustomRow) return null;
    
    switch (config.customRowType) {
      case 'empty':
        return (
          <svg className="h-4 w-4 text-gray-500" fill="currentColor" viewBox="0 0 20 20">
            <path fillRule="evenodd" d="M3 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clipRule="evenodd" />
          </svg>
        );
      case 'separator':
        return (
          <svg className="h-4 w-4 text-gray-500" fill="currentColor" viewBox="0 0 20 20">
            <path fillRule="evenodd" d="M3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clipRule="evenodd" />
          </svg>
        );
      case 'note':
        return (
          <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>
        );
      default:
        return null;
    }
  };

  return (
    <div
      draggable={enableDragging}
      className={cn(
        "flex items-center justify-between py-3 px-4 rounded-lg transition-all duration-200 border group",
        config.isVisible ? "border-green-200 bg-green-50/30" : "border-gray-200 bg-gray-50/30",
        isDragging && "opacity-50 scale-95 rotate-2",
        isDragOver && "bg-blue-50 border-blue-300 border-t-2",
        isHovered && !isDragging && "shadow-sm",
        config.isCustomRow && "border-dashed"
      )}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      onDragStart={handleDragStart}
      onDragEnd={onDragEnd}
      onDragEnter={() => onDragEnter(index)}
      onDragLeave={onDragLeave}
      onDragOver={onDragOver}
      onDrop={onDrop}
    >
      <div className="flex items-center gap-3 flex-1 min-w-0">
        {/* 拖拽手柄 */}
        {enableDragging && (
          <div className={cn(
            "cursor-grab active:cursor-grabbing p-1 hover:bg-gray-200 rounded transition-opacity",
            isHovered ? "opacity-100" : "opacity-0"
          )}>
            <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={cn(
          "w-2 h-2 rounded-full flex-shrink-0",
          config.isVisible ? "bg-green-500" : "bg-gray-400"
        )} />

        {/* 行类型图标 */}
        {getRowTypeIcon()}

        {/* 显示文本 */}
        <span className={cn(
          "text-sm font-medium truncate",
          config.isVisible ? "text-gray-900" : "text-gray-500",
          config.isCustomRow && "italic"
        )}>
          {displayText}
          {config.isCustomRow && (
            <span className="text-xs text-gray-400 ml-2">
              ({config.customRowType === 'empty' && '空行'})
              ({config.customRowType === 'separator' && '分隔线'})
              ({config.customRowType === 'note' && '备注'})
            </span>
          )}
        </span>

        {/* 排序序号 */}
        <span className="text-xs text-gray-400 bg-gray-100 px-2 py-1 rounded">
          #{(config.displayOrder ?? 0) + 1}
        </span>
      </div>

      <div className="flex items-center gap-2 ml-3">
        {/* 删除自定义行按钮 */}
        {config.isCustomRow && onDeleteCustomRow && (
          <button
            onClick={handleDeleteCustomRow}
            className="p-1 text-red-400 hover:text-red-600 hover:bg-red-50 rounded transition-colors"
            title="删除此行"
          >
            <svg className="h-4 w-4" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clipRule="evenodd" />
            </svg>
          </button>
        )}

        {/* 可见性切换开关 */}
        <label className="flex items-center cursor-pointer">
          <input
            type="checkbox"
            checked={config.isVisible}
            onChange={(e) => onVisibilityChange(rowId, e.target.checked)}
            className="sr-only"
          />
          <div className={cn(
            "relative inline-flex h-6 w-11 items-center rounded-full transition-colors duration-200 ease-in-out focus-within:ring-2 focus-within:ring-blue-500 focus-within:ring-offset-2",
            config.isVisible ? "bg-blue-600" : "bg-gray-300"
          )}>
            <span className={cn(
              "inline-block h-5 w-5 transform rounded-full bg-white shadow-lg transition-transform duration-200 ease-in-out",
              config.isVisible ? "translate-x-5" : "translate-x-0.5"
            )} />
          </div>
        </label>
      </div>
    </div>
  );
}