import { useState } from 'react';
import type { ItemField } from '@/contexts/ItemMasterContext';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  GripVertical,
  Edit,
  Unlink
} from 'lucide-react';
import { ReorderButtons } from '@/components/molecules';

// 입력방식 옵션 (ItemMasterDataManagement에서 사용하는 상수)
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;
  // 2025-12-03: ID 기반으로 변경 (index는 stale 문제 발생)
  moveField: (dragFieldId: number, hoverFieldId: number) => void;
  onDelete: () => void;
  onEdit?: () => void;
  prevFieldId?: number;
  nextFieldId?: number;
}

export function DraggableField({ field, index: _index, moveField, onDelete, onEdit, prevFieldId, nextFieldId }: DraggableFieldProps) {
  const [isDragging, setIsDragging] = useState(false);

  const handleDragStart = (e: React.DragEvent) => {
    e.stopPropagation(); // 2025-12-03: 섹션 드래그 이벤트와 충돌 방지
    e.dataTransfer.effectAllowed = 'move';
    // 2025-12-03: 타입 구분 추가 (섹션/필드 드래그 구분)
    e.dataTransfer.setData('application/json', JSON.stringify({ type: 'field', id: field.id }));
    setIsDragging(true);
  };

  const handleDragEnd = () => {
    setIsDragging(false);
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation(); // 2025-12-03: 이벤트 버블링 방지
    e.dataTransfer.dropEffect = 'move';
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation(); // 2025-12-03: 이벤트 버블링 방지
    try {
      const data = JSON.parse(e.dataTransfer.getData('application/json'));
      // 2025-12-03: 타입 체크 - 필드 드래그만 처리
      if (data.type !== 'field') {
        return;
      }
      if (data.id !== field.id) {
        moveField(data.id, field.id);
      }
    } catch {
      // Ignore - 다른 타입의 드래그 데이터
    }
  };

  return (
    <div
      draggable
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
      onDragOver={handleDragOver}
      onDrop={handleDrop}
      className={`flex items-center justify-between p-3 border rounded hover:bg-gray-50 transition-opacity ${
        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 hidden md:block" />
          <ReorderButtons
            onMoveUp={() => prevFieldId !== undefined && moveField(field.id, prevFieldId)}
            onMoveDown={() => nextFieldId !== undefined && moveField(field.id, nextFieldId)}
            isFirst={prevFieldId === undefined}
            isLast={nextFieldId === undefined}
            size="xs"
          />
          <span className="text-sm">{field.field_name}</span>
          <Badge variant="outline" className="text-xs">
            {INPUT_TYPE_OPTIONS.find(t => t.value === field.field_type)?.label || field.field_type}
          </Badge>
          {(field.is_required || field.properties?.required) && (
            <Badge variant="destructive" className="text-xs">필수</Badge>
          )}
          {field.display_condition && (
            <Badge variant="secondary" className="text-xs">조건부</Badge>
          )}
          {field.order_no !== undefined && (
            <Badge variant="outline" className="text-xs">순서: {field.order_no + 1}</Badge>
          )}
        </div>
        <div className="ml-6 text-xs text-gray-500 mt-1">
          필드ID: {field.id}
          {field.display_condition && (
            <span className="ml-2">
              (조건부 표시 설정됨)
            </span>
          )}
          {field.placeholder && (
            <span className="ml-2">• {field.placeholder}</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}
          title="섹션에서 연결 해제"
        >
          <Unlink className="h-4 w-4 text-orange-500" />
        </Button>
      </div>
    </div>
  );
}