/**
 * Advanced Drag-and-Drop Components
 * Enhanced section reordering with visual feedback and smooth animations
 */

"use client";

import React, { useState, useCallback } from "react";
import {
  DragDropContext,
  Droppable,
  Draggable,
  DropResult,
  DragUpdate,
} from "@hello-pangea/dnd";
import { useEditor } from "./context";
import { BaseSection } from "./types";

// Icon mapping for drag and drop UI
const iconMap: Record<string, string> = {
  drag: "⋮⋮",
  delete: "🗑️",
  copy: "📋",
  eye: "👁️",
  eyeOff: "🙈",
  settings: "⚙️",
  hero: "🎯",
  features: "⭐",
  cta: "🔔",
  pricing: "💰",
  testimonials: "💬",
  contact: "📞",
  gallery: "🖼️",
  text: "📝",
  custom: "🔧",
};

// Enhanced Section Item Component with Drag-and-Drop
interface DraggableSectionItemProps {
  section: BaseSection;
  index: number;
  isSelected: boolean;
  isDragDisabled?: boolean;
  onSelect: (sectionId: string) => void;
  onDelete: (sectionId: string) => void;
  onDuplicate: (sectionId: string) => void;
  onToggleVisibility: (sectionId: string) => void;
  onSettings: (sectionId: string) => void;
}

export function DraggableSectionItem({
  section,
  index,
  isSelected,
  isDragDisabled = false,
  onSelect,
  onDelete,
  onDuplicate,
  onToggleVisibility,
  onSettings,
}: DraggableSectionItemProps) {
  const [isHovering, setIsHovering] = useState(false);
  const [showActions, setShowActions] = useState(false);

  const handleMouseEnter = useCallback(() => {
    setIsHovering(true);
    setShowActions(true);
  }, []);

  const handleMouseLeave = useCallback(() => {
    setIsHovering(false);
    setTimeout(() => setShowActions(false), 300); // Delay to allow clicking actions
  }, []);

  return (
    <Draggable
      draggableId={section.id}
      index={index}
      isDragDisabled={isDragDisabled}
    >
      {(provided, snapshot) => (
        <div
          ref={provided.innerRef}
          {...provided.draggableProps}
          className={`
            group relative bg-white rounded-lg border-2 transition-all duration-200 cursor-pointer
            ${
              snapshot.isDragging
                ? "border-blue-400 shadow-lg scale-105 rotate-2 z-50"
                : isSelected
                ? "border-blue-500 shadow-md"
                : isHovering
                ? "border-gray-300 shadow-sm"
                : "border-gray-200"
            }
            ${!section.isActive ? "opacity-60" : ""}
            ${isDragDisabled ? "cursor-not-allowed" : ""}
          `}
          onClick={() => onSelect(section.id)}
          onMouseEnter={handleMouseEnter}
          onMouseLeave={handleMouseLeave}
          style={provided.draggableProps.style}
        >
          {/* Drag Handle */}
          <div
            {...provided.dragHandleProps}
            className={`
              absolute left-2 top-1/2 transform -translate-y-1/2 
              opacity-0 group-hover:opacity-100 transition-opacity duration-200
              ${snapshot.isDragging ? "opacity-100" : ""}
              ${
                isDragDisabled
                  ? "cursor-not-allowed opacity-30"
                  : "cursor-grab active:cursor-grabbing"
              }
            `}
          >
            <span className="text-gray-400 text-lg leading-none select-none">
              {iconMap.drag}
            </span>
          </div>

          {/* Section Content */}
          <div className="p-4 pl-10">
            <div className="flex items-start justify-between">
              <div className="flex-1 min-w-0">
                <div className="flex items-center space-x-3 mb-2">
                  <span className="text-2xl flex-shrink-0">
                    {iconMap[section.type] || iconMap.custom}
                  </span>
                  <div className="min-w-0 flex-1">
                    <h4 className="text-sm font-semibold text-gray-900 truncate">
                      {section.name}
                    </h4>
                    <p className="text-xs text-gray-500 capitalize">
                      {section.type}
                    </p>
                  </div>
                </div>

                {/* Section Status Indicators */}
                <div className="flex items-center space-x-2">
                  <span
                    className={`
                    inline-flex items-center px-2 py-1 rounded-full text-xs font-medium
                    ${
                      section.isActive
                        ? "bg-green-100 text-green-800"
                        : "bg-gray-100 text-gray-800"
                    }
                  `}
                  >
                    {section.isActive ? "활성" : "비활성"}
                  </span>

                  {section.settings.isLocked && (
                    <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-orange-100 text-orange-800">
                      🔒 잠김
                    </span>
                  )}

                  <span className="text-xs text-gray-400">
                    #{section.order + 1}
                  </span>
                </div>
              </div>

              {/* Action Buttons */}
              <div
                className={`
                flex items-center space-x-1 transition-opacity duration-200
                ${showActions || isSelected ? "opacity-100" : "opacity-0"}
              `}
              >
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    onToggleVisibility(section.id);
                  }}
                  className="p-1 text-gray-400 hover:text-gray-600 transition-colors"
                  title={section.isActive ? "숨기기" : "표시"}
                >
                  {section.isActive ? iconMap.eye : iconMap.eyeOff}
                </button>

                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    onSettings(section.id);
                  }}
                  className="p-1 text-gray-400 hover:text-blue-600 transition-colors"
                  title="설정"
                >
                  {iconMap.settings}
                </button>

                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    onDuplicate(section.id);
                  }}
                  className="p-1 text-gray-400 hover:text-green-600 transition-colors"
                  title="복제"
                >
                  {iconMap.copy}
                </button>

                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    onDelete(section.id);
                  }}
                  className="p-1 text-gray-400 hover:text-red-600 transition-colors"
                  title="삭제"
                >
                  {iconMap.delete}
                </button>
              </div>
            </div>

            {/* Drag Overlay for Visual Feedback */}
            {snapshot.isDragging && (
              <div className="absolute inset-0 bg-blue-50 border-2 border-dashed border-blue-300 rounded-lg flex items-center justify-center">
                <span className="text-blue-600 font-medium">이동 중...</span>
              </div>
            )}
          </div>
        </div>
      )}
    </Draggable>
  );
}

// Drop Zone Indicator Component
interface DropZoneIndicatorProps {
  isOver: boolean;
  canDrop: boolean;
}

function DropZoneIndicator({ isOver, canDrop }: DropZoneIndicatorProps) {
  if (!canDrop) return null;

  return (
    <div
      className={`
      h-2 mx-4 my-1 rounded-full transition-all duration-200
      ${isOver ? "bg-blue-400 shadow-lg transform scale-110" : "bg-blue-200"}
    `}
    />
  );
}

// Enhanced Droppable Section List
interface DroppableSectionListProps {
  sections: BaseSection[];
  selectedSection: string | null;
  onSectionSelect: (sectionId: string) => void;
  onSectionReorder: (startIndex: number, endIndex: number) => void;
  onSectionDelete: (sectionId: string) => void;
  onSectionDuplicate: (sectionId: string) => void;
  onSectionToggleVisibility: (sectionId: string) => void;
  onSectionSettings: (sectionId: string) => void;
  isDragDisabled?: boolean;
  className?: string;
}

export function DroppableSectionList({
  sections,
  selectedSection,
  onSectionSelect,
  onSectionReorder,
  onSectionDelete,
  onSectionDuplicate,
  onSectionToggleVisibility,
  onSectionSettings,
  isDragDisabled = false,
  className = "",
}: DroppableSectionListProps) {
  const [draggedOverIndex, setDraggedOverIndex] = useState<number | null>(null);

  const handleDragEnd = useCallback(
    (result: DropResult) => {
      setDraggedOverIndex(null);

      if (
        !result.destination ||
        result.destination.index === result.source.index
      ) {
        return;
      }

      onSectionReorder(result.source.index, result.destination.index);
    },
    [onSectionReorder]
  );

  const handleDragUpdate = useCallback((update: DragUpdate) => {
    setDraggedOverIndex(update.destination?.index ?? null);
  }, []);

  // Sort sections by order
  const sortedSections = [...sections].sort((a, b) => a.order - b.order);

  return (
    <div className={`space-y-3 ${className}`}>
      <DragDropContext
        onDragEnd={handleDragEnd}
        onDragUpdate={handleDragUpdate}
      >
        <Droppable droppableId="sections-list">
          {(provided, snapshot) => (
            <div
              ref={provided.innerRef}
              {...provided.droppableProps}
              className={`
                transition-colors duration-200 rounded-lg p-2
                ${snapshot.isDraggingOver ? "bg-blue-50" : "bg-transparent"}
              `}
            >
              {sortedSections.length === 0 ? (
                <div className="text-center py-12 text-gray-500">
                  <div className="text-4xl mb-4">📄</div>
                  <p className="text-lg font-medium mb-2">섹션이 없습니다</p>
                  <p className="text-sm">
                    템플릿을 선택하여 새 섹션을 추가하세요
                  </p>
                </div>
              ) : (
                <>
                  {sortedSections.map((section, index) => (
                    <React.Fragment key={section.id}>
                      {index === 0 && draggedOverIndex === 0 && (
                        <DropZoneIndicator isOver={true} canDrop={true} />
                      )}

                      <DraggableSectionItem
                        section={section}
                        index={index}
                        isSelected={selectedSection === section.id}
                        isDragDisabled={
                          isDragDisabled || section.settings.isLocked
                        }
                        onSelect={onSectionSelect}
                        onDelete={onSectionDelete}
                        onDuplicate={onSectionDuplicate}
                        onToggleVisibility={onSectionToggleVisibility}
                        onSettings={onSectionSettings}
                      />

                      {draggedOverIndex === index + 1 && (
                        <DropZoneIndicator isOver={true} canDrop={true} />
                      )}
                    </React.Fragment>
                  ))}
                </>
              )}
              {provided.placeholder}
            </div>
          )}
        </Droppable>
      </DragDropContext>
    </div>
  );
}

// Section Bulk Actions Component
interface SectionBulkActionsProps {
  selectedSections: string[];
  onBulkDelete: (sectionIds: string[]) => void;
  onBulkToggleVisibility: (sectionIds: string[], visible: boolean) => void;
  onBulkDuplicate: (sectionIds: string[]) => void;
  onClearSelection: () => void;
}

export function SectionBulkActions({
  selectedSections,
  onBulkDelete,
  onBulkToggleVisibility,
  onBulkDuplicate,
  onClearSelection,
}: SectionBulkActionsProps) {
  if (selectedSections.length === 0) return null;

  return (
    <div className="bg-blue-50 border border-blue-200 rounded-lg p-3 mb-4">
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-3">
          <span className="text-sm font-medium text-blue-900">
            {selectedSections.length}개 섹션 선택됨
          </span>
          <div className="flex items-center space-x-2">
            <button
              onClick={() => onBulkToggleVisibility(selectedSections, true)}
              className="px-3 py-1 text-xs bg-green-100 hover:bg-green-200 text-green-800 rounded"
            >
              모두 표시
            </button>
            <button
              onClick={() => onBulkToggleVisibility(selectedSections, false)}
              className="px-3 py-1 text-xs bg-gray-100 hover:bg-gray-200 text-gray-800 rounded"
            >
              모두 숨김
            </button>
            <button
              onClick={() => onBulkDuplicate(selectedSections)}
              className="px-3 py-1 text-xs bg-blue-100 hover:bg-blue-200 text-blue-800 rounded"
            >
              복제
            </button>
            <button
              onClick={() => onBulkDelete(selectedSections)}
              className="px-3 py-1 text-xs bg-red-100 hover:bg-red-200 text-red-800 rounded"
            >
              삭제
            </button>
          </div>
        </div>

        <button
          onClick={onClearSelection}
          className="text-xs text-blue-600 hover:text-blue-800"
        >
          선택 해제
        </button>
      </div>
    </div>
  );
}

// Enhanced Section List with All Features
interface EnhancedSectionListProps {
  className?: string;
}

export function EnhancedSectionList({
  className = "",
}: EnhancedSectionListProps) {
  const {
    state,
    selectSection,
    deleteSection,
    duplicateSection,
    moveSection,
    updateSection,
  } = useEditor();

  const [selectedSections, setSelectedSections] = useState<string[]>([]);
  const [isDragDisabled, setIsDragDisabled] = useState(false);

  // Handle section reordering
  const handleSectionReorder = useCallback(
    (startIndex: number, endIndex: number) => {
      const sortedSections = [...state.sections].sort(
        (a, b) => a.order - b.order
      );
      const sectionToMove = sortedSections[startIndex];

      if (sectionToMove) {
        moveSection(sectionToMove.id, endIndex);
      }
    },
    [state.sections, moveSection]
  );

  // Handle section selection
  const handleSectionSelect = useCallback(
    (sectionId: string) => {
      selectSection(sectionId);

      // Handle multi-selection with Ctrl/Cmd key
      // This would need keyboard event handling in a real implementation
      setSelectedSections([sectionId]);
    },
    [selectSection]
  );

  // Handle visibility toggle
  const handleToggleVisibility = useCallback(
    (sectionId: string) => {
      const section = state.sections.find((s) => s.id === sectionId);
      if (section) {
        updateSection(sectionId, { isActive: !section.isActive });
      }
    },
    [state.sections, updateSection]
  );

  // Handle section settings
  const handleSectionSettings = useCallback(
    (sectionId: string) => {
      selectSection(sectionId);
      // Additional settings logic would go here
    },
    [selectSection]
  );

  // Bulk operations
  const handleBulkDelete = useCallback(
    (sectionIds: string[]) => {
      if (confirm(`${sectionIds.length}개 섹션을 삭제하시겠습니까?`)) {
        sectionIds.forEach((id) => deleteSection(id));
        setSelectedSections([]);
      }
    },
    [deleteSection]
  );

  const handleBulkToggleVisibility = useCallback(
    (sectionIds: string[], visible: boolean) => {
      sectionIds.forEach((id) => {
        updateSection(id, { isActive: visible });
      });
    },
    [updateSection]
  );

  const handleBulkDuplicate = useCallback(
    (sectionIds: string[]) => {
      sectionIds.forEach((id) => duplicateSection(id));
      setSelectedSections([]);
    },
    [duplicateSection]
  );

  return (
    <div className={`w-80 bg-gray-50 border-r overflow-y-auto ${className}`}>
      <div className="p-4">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-semibold text-gray-900">섹션 관리</h3>
          <div className="flex items-center space-x-2">
            <span className="text-sm text-gray-500">
              {state.sections.length}개
            </span>
            <button
              onClick={() => setIsDragDisabled(!isDragDisabled)}
              className={`
                px-2 py-1 text-xs rounded transition-colors
                ${
                  isDragDisabled
                    ? "bg-red-100 text-red-800 hover:bg-red-200"
                    : "bg-green-100 text-green-800 hover:bg-green-200"
                }
              `}
              title={isDragDisabled ? "드래그 활성화" : "드래그 비활성화"}
            >
              🔒 {isDragDisabled ? "잠김" : "열림"}
            </button>
          </div>
        </div>

        <SectionBulkActions
          selectedSections={selectedSections}
          onBulkDelete={handleBulkDelete}
          onBulkToggleVisibility={handleBulkToggleVisibility}
          onBulkDuplicate={handleBulkDuplicate}
          onClearSelection={() => setSelectedSections([])}
        />

        <DroppableSectionList
          sections={state.sections}
          selectedSection={state.selectedSection}
          onSectionSelect={handleSectionSelect}
          onSectionReorder={handleSectionReorder}
          onSectionDelete={deleteSection}
          onSectionDuplicate={duplicateSection}
          onSectionToggleVisibility={handleToggleVisibility}
          onSectionSettings={handleSectionSettings}
          isDragDisabled={isDragDisabled}
        />
      </div>
    </div>
  );
}
