"use client";

import { memo, useCallback, useRef, useState, type DragEvent } from "react";
import { reorderCustomMethodCardFieldBlocks } from "../../../../../lib/create/reorderCustomMethodCardFieldBlocks";
import { CustomMethodCardWizardBlocksListView } from "./CustomMethodCardWizardBlocksList.view";
import type { CustomMethodCardWizardBlocksListProps } from "./CustomMethodCardWizardBlocksList.types";

function CustomMethodCardWizardBlocksListContainerComponent({
  blocks,
  fieldTypeLabels,
  dragHandleAriaLabel,
  listLabel,
  onBlocksReorder,
  onEditBlock,
}: CustomMethodCardWizardBlocksListProps) {
  const [draggingIndex, setDraggingIndex] = useState<number | null>(null);
  const [overIndex, setOverIndex] = useState<number | null>(null);
  const draggingIndexRef = useRef<number | null>(null);
  const dragFromHandleRef = useRef(false);

  const clearDragUi = useCallback(() => {
    draggingIndexRef.current = null;
    dragFromHandleRef.current = false;
    setDraggingIndex(null);
    setOverIndex(null);
  }, []);

  const handleHandlePointerDown = useCallback(() => {
    dragFromHandleRef.current = true;
  }, []);

  const handleDragStart = useCallback(
    (index: number) => (e: DragEvent) => {
      if (!dragFromHandleRef.current) {
        e.preventDefault();
        return;
      }
      e.dataTransfer.effectAllowed = "move";
      e.dataTransfer.setData("text/plain", String(index));
      draggingIndexRef.current = index;
      setDraggingIndex(index);
    },
    [],
  );

  const handleDragOver = useCallback((index: number) => {
    return (e: DragEvent) => {
      e.preventDefault();
      e.dataTransfer.dropEffect = "move";
      setOverIndex(index);
    };
  }, []);

  const handleDrop = useCallback(
    (index: number) => (e: DragEvent) => {
      e.preventDefault();
      const fromData = Number.parseInt(e.dataTransfer.getData("text/plain"), 10);
      const from = Number.isNaN(fromData)
        ? draggingIndexRef.current
        : fromData;
      if (from == null || Number.isNaN(from)) {
        clearDragUi();
        return;
      }
      onBlocksReorder(
        reorderCustomMethodCardFieldBlocks(blocks, from, index),
      );
      clearDragUi();
    },
    [blocks, clearDragUi, onBlocksReorder],
  );

  return (
    <CustomMethodCardWizardBlocksListView
      blocks={blocks}
      fieldTypeLabels={fieldTypeLabels}
      dragHandleAriaLabel={dragHandleAriaLabel}
      listLabel={listLabel}
      onBlocksReorder={onBlocksReorder}
      draggingIndex={draggingIndex}
      overIndex={overIndex}
      onDragStart={handleDragStart}
      onDragOver={handleDragOver}
      onDrop={handleDrop}
      onDragEnd={clearDragUi}
      onHandlePointerDown={handleHandlePointerDown}
      onEditBlock={onEditBlock}
    />
  );
}

export const CustomMethodCardWizardBlocksList = memo(
  CustomMethodCardWizardBlocksListContainerComponent,
);
CustomMethodCardWizardBlocksList.displayName =
  "CustomMethodCardWizardBlocksList";
