import { useState } from 'react';
import type { ItemSection } from '@/contexts/ItemMasterContext';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  GripVertical,
  FileText,
  Edit,
  Check,
  X,
  Unlink
} from 'lucide-react';
import { ReorderButtons } from '@/components/molecules';

interface DraggableSectionProps {
  section: ItemSection;
  index: number;
  totalSections: number;
  moveSection: (dragIndex: number, hoverIndex: number) => void;
  onDelete: () => void;
  onEditTitle: (id: number, title: string) => void;
  editingSectionId: number | null;
  editingSectionTitle: string;
  setEditingSectionTitle: (title: string) => void;
  setEditingSectionId: (id: number | null) => void;
  handleSaveSectionTitle: () => void;
  children: React.ReactNode;
}

export function DraggableSection({
  section,
  index,
  totalSections,
  moveSection,
  onDelete,
  onEditTitle,
  editingSectionId,
  editingSectionTitle,
  setEditingSectionTitle,
  setEditingSectionId,
  handleSaveSectionTitle,
  children
}: DraggableSectionProps) {
  const [isDragging, setIsDragging] = useState(false);

  const handleDragStart = (e: React.DragEvent) => {
    e.dataTransfer.effectAllowed = 'move';
    // 2025-12-03: 타입 구분 추가 (섹션/필드 드래그 구분)
    e.dataTransfer.setData('application/json', JSON.stringify({ type: 'section', index, id: section.id }));
    setIsDragging(true);
  };

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

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    try {
      const data = JSON.parse(e.dataTransfer.getData('application/json'));
      // 2025-12-03: 타입 체크 - 섹션 드래그만 처리
      if (data.type !== 'section') {
        return;
      }
      if (data.index !== index) {
        moveSection(data.index, index);
      }
    } catch {
      // Ignore - 다른 타입의 드래그 데이터
    }
  };

  return (
    <div
      draggable
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
      onDragOver={handleDragOver}
      onDrop={handleDrop}
      className={`border rounded-lg overflow-hidden transition-opacity ${
        isDragging ? 'opacity-50' : 'opacity-100'
      }`}
    >
      {/* 섹션 헤더 */}
      <div className="bg-blue-50 border-b p-3">
        <div className="flex items-center justify-between gap-2">
          <div className="flex items-center gap-2 flex-1 min-w-0">
            <GripVertical className="h-4 w-4 text-gray-400 hidden md:block" style={{ cursor: 'move' }} />
            <ReorderButtons
              onMoveUp={() => moveSection(index, index - 1)}
              onMoveDown={() => moveSection(index, index + 1)}
              isFirst={index === 0}
              isLast={index === totalSections - 1}
              size="xs"
            />
            <FileText className="h-4 w-4 text-blue-600" />
            {editingSectionId === section.id ? (
              <div className="flex items-center gap-2 flex-1">
                <Input
                  value={editingSectionTitle}
                  onChange={(e) => setEditingSectionTitle(e.target.value)}
                  className="h-8 bg-white"
                  autoFocus
                  onKeyDown={(e) => {
                    if (e.key === 'Enter') handleSaveSectionTitle();
                    if (e.key === 'Escape') setEditingSectionId(null);
                  }}
                />
                <Button size="sm" onClick={handleSaveSectionTitle}>
                  <Check className="h-4 w-4" />
                </Button>
                <Button size="sm" variant="ghost" onClick={() => setEditingSectionId(null)}>
                  <X className="h-4 w-4" />
                </Button>
              </div>
            ) : (
              <div
                className="flex items-center gap-2 flex-1 cursor-pointer group min-w-0"
                onClick={() => onEditTitle(section.id, section.title)}
              >
                <span className="text-blue-900 truncate text-sm sm:text-base">{section.title}</span>
                <Edit className="h-3 w-3 text-gray-400 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0" />
              </div>
            )}
          </div>
          <div className="flex items-center gap-1 flex-shrink-0">
            <Button
              size="sm"
              variant="ghost"
              onClick={onDelete}
              title="페이지에서 연결 해제"
            >
              <Unlink className="h-4 w-4 text-orange-500" />
            </Button>
          </div>
        </div>
      </div>

      {/* 섹션 컨텐츠 */}
      <div className="p-4 bg-white space-y-2">
        {children}
      </div>
    </div>
  );
}