import React, { useCallback, useRef, useState } from 'react';
import { GripVertical } from 'lucide-react';
import type { MemoBlockCandidate } from '../../../types/research';

interface MemoOutlineRailProps {
  blocks: MemoBlockCandidate[];
  onInsertBlock: (block: MemoBlockCandidate) => void;
  onReorderBlocks?: (reordered: MemoBlockCandidate[]) => void;
}

export const MemoOutlineRail: React.FC<MemoOutlineRailProps> = ({
  blocks,
  onInsertBlock,
  onReorderBlocks,
}) => {
  const [dragIndex, setDragIndex] = useState<number | null>(null);
  const [dropTarget, setDropTarget] = useState<number | null>(null);
  const longPressTimer = useRef<ReturnType<typeof setTimeout>>(undefined);

  const handleDragStart = useCallback((index: number) => {
    setDragIndex(index);
  }, []);

  const handleDragEnter = useCallback((index: number) => {
    if (dragIndex === null || dragIndex === index) return;
    setDropTarget(index);
  }, [dragIndex]);

  const handleDragEnd = useCallback(() => {
    if (dragIndex !== null && dropTarget !== null && dragIndex !== dropTarget && onReorderBlocks) {
      const reordered = [...blocks];
      const [moved] = reordered.splice(dragIndex, 1);
      reordered.splice(dropTarget, 0, moved);
      onReorderBlocks(reordered);
    }
    setDragIndex(null);
    setDropTarget(null);
  }, [blocks, dragIndex, dropTarget, onReorderBlocks]);

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
  }, []);

  const handleTouchStart = useCallback((index: number) => {
    longPressTimer.current = setTimeout(() => {
      setDragIndex(index);
    }, 300);
  }, []);

  const handleTouchEnd = useCallback(() => {
    if (longPressTimer.current) {
      clearTimeout(longPressTimer.current);
    }
    if (dragIndex !== null) {
      if (dropTarget !== null && dragIndex !== dropTarget && onReorderBlocks) {
        const reordered = [...blocks];
        const [moved] = reordered.splice(dragIndex, 1);
        reordered.splice(dropTarget, 0, moved);
        onReorderBlocks(reordered);
      }
      setDragIndex(null);
      setDropTarget(null);
    }
  }, [blocks, dragIndex, dropTarget, onReorderBlocks]);

  return (
    <div className="space-y-2 border border-term-border bg-term-surface p-4">
      <div>
        <h3 className="text-xs uppercase tracking-[0.2em] text-term-text-tertiary">Memo Outline</h3>
        <p className="mt-1 text-xs text-term-text-tertiary">Promote these section candidates into the draft.</p>
      </div>
      {blocks.length === 0 ? (
        <p className="text-sm text-term-text-muted">No memo blocks generated yet.</p>
      ) : (
        blocks.map((block, index) => {
          const isDragging = dragIndex === index;
          const isDropTarget = dropTarget === index && dragIndex !== index;

          return (
            <div
              key={`${block.sectionKind}-${block.headline}-${index}`}
              draggable={onReorderBlocks != null}
              onDragStart={() => handleDragStart(index)}
              onDragEnter={() => handleDragEnter(index)}
              onDragEnd={handleDragEnd}
              onDragOver={handleDragOver}
              onTouchStart={() => handleTouchStart(index)}
              onTouchEnd={handleTouchEnd}
              className={`flex items-center gap-2 transition-colors ${
                isDropTarget ? 'border-t-2 border-t-info/60' : ''
              } ${isDragging ? 'opacity-50' : ''}`}
            >
              {onReorderBlocks && (
                <div className="flex-shrink-0 cursor-grab text-term-text-tertiary hover:text-term-text">
                  <GripVertical className="w-3.5 h-3.5" />
                </div>
              )}
              <button
                type="button"
                onClick={() => onInsertBlock(block)}
                className="w-full border border-term-border bg-term-bg px-3 py-3 text-left transition-colors hover:border-info/50"
              >
                <div className="text-[10px] uppercase tracking-[0.18em] text-term-text-tertiary">
                  {block.sectionKind.replace(/_/g, ' ')}
                </div>
                <div className="mt-1 text-sm font-semibold text-term-text">{block.headline}</div>
                <div className="mt-1 text-xs text-term-text-tertiary">{Math.round(block.confidence * 100)}% confidence</div>
              </button>
            </div>
          );
        })
      )}
    </div>
  );
};
