import { useRef } from 'react';
import { useDrag, useDrop } from 'react-dnd';
import type { ItemField } from './contexts/DataContext';
import { GripVertical, X, Edit } from 'lucide-react';
import { Badge } from './ui/badge';
import { Button } from './ui/button';

const INPUT_TYPE_OPTIONS = [
  { value: 'textbox', label: '텍스트박스' },
  { value: 'dropdown', label: '드롭다운' },
  { value: 'checkbox', label: '체크박스' },
  { value: 'number', label: '숫자' },
  { value: 'date', label: '날짜' },
  { value: 'textarea', label: '텍스트영역' }
];

interface DraggableFieldProps {
  field: ItemField;
  index: number;
  moveField: (dragIndex: number, hoverIndex: number) => void;
  onDelete: () => void;
  onEdit?: () => void;
}

interface DragItem {
  type: string;
  index: number;
  id: string;
}

export function DraggableField({ field, index, moveField, onDelete, onEdit }: DraggableFieldProps) {
  const ref = useRef<HTMLDivElement>(null);

  const [{ isDragging }, drag] = useDrag<DragItem, void, { isDragging: boolean }>({
    type: 'field',
    item: { type: 'field', index, id: field.id },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });

  const [, drop] = useDrop<DragItem, void, {}>({
    accept: 'field',
    hover(item: DragItem) {
      if (!ref.current) {
        return;
      }
      const dragIndex = item.index;
      const hoverIndex = index;

      if (dragIndex === hoverIndex) {
        return;
      }

      moveField(dragIndex, hoverIndex);
      item.index = hoverIndex;
    },
  });

  drag(drop(ref));

  return (
    <div
      ref={ref}
      className={`flex items-center justify-between p-3 border rounded hover:bg-gray-50 transition-colors ${
        isDragging ? 'opacity-50' : 'opacity-100'
      }`}
      style={{ cursor: 'move' }}
    >
      <div className="flex-1">
        <div className="flex items-center gap-2">
          <GripVertical className="h-4 w-4 text-gray-400" />
          <span className="text-sm font-medium">{field.name}</span>
          <Badge variant="outline" className="text-xs">
            {INPUT_TYPE_OPTIONS.find(t => t.value === field.property.inputType)?.label}
          </Badge>
          {field.property.required && (
            <Badge variant="destructive" className="text-xs">필수</Badge>
          )}
          {field.displayCondition && (
            <Badge variant="secondary" className="text-xs">조건부</Badge>
          )}
          {field.order !== undefined && (
            <Badge variant="outline" className="text-xs">순서: {field.order + 1}</Badge>
          )}
        </div>
        <div className="ml-6 text-xs text-gray-500 mt-1">
          필드키: {field.fieldKey}
          {field.displayCondition && (
            <span className="ml-2">
              (조건: {field.displayCondition.fieldKey} = {field.displayCondition.expectedValue})
            </span>
          )}
          {field.description && (
            <span className="ml-2">• {field.description}</span>
          )}
        </div>
      </div>
      <div className="flex gap-2">
        {onEdit && (
          <Button 
            size="sm" 
            variant="ghost" 
            onClick={onEdit}
          >
            <Edit className="h-4 w-4 text-blue-500" />
          </Button>
        )}
        <Button 
          size="sm" 
          variant="ghost" 
          onClick={onDelete}
        >
          <X className="h-4 w-4 text-red-500" />
        </Button>
      </div>
    </div>
  );
}