import React, { useState } from 'react';
import { FileText, MoreHorizontal } from 'lucide-react';
import { SidebarMenuSubItem, SidebarMenuSubButton, SidebarMenuAction } from '@/components/ui/sidebar';
import { Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';

const ApiDropdownMenu = ({ onOpen, onRename, onDelete }) => (
    <DropdownMenu>
      <DropdownMenuTrigger data-dropdown-trigger="true" className="p-0 h-auto">
        <div className="hover:bg-accent rounded-sm">
          <MoreHorizontal className="h-4 w-4"/>
        </div>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end">
        <DropdownMenuItem onClick={onOpen}>
          Open
        </DropdownMenuItem>
        <DropdownMenuSeparator/>
        <DropdownMenuItem onClick={onRename}>
          Rename
        </DropdownMenuItem>
        <DropdownMenuItem className="text-destructive" onClick={onDelete}>
          Delete
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
);

const DraggableApiItem = ({ api, collectionId, onApiAction }) => {
  const [isDragging, setIsDragging] = useState(false);

  const handleDragStart = (event) => {
    // Prepare API data for drag operation
    const apiData = {...api};

    // Create drag image for better visual feedback
    const dragImage = document.createElement('div');
    dragImage.className = 'bg-white border rounded-md shadow-lg p-2 text-sm';
    dragImage.textContent = `${apiData.method} ${apiData.name}`;
    document.body.appendChild(dragImage);

    // Set drag image and offset
    event.dataTransfer.setDragImage(dragImage, 0, 0);

    // Clean up the drag image after it's no longer needed
    requestAnimationFrame(() => {
      document.body.removeChild(dragImage);
    });

    // Set the drag data
    event.dataTransfer.setData('application/json', JSON.stringify(apiData));
    event.dataTransfer.effectAllowed = 'copy';

    setIsDragging(true);
  };

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

  return (
      <SidebarMenuSubItem
          draggable
          onDragStart={handleDragStart}
          onDragEnd={handleDragEnd}
          className={`cursor-move transition-colors duration-200 ${
              isDragging ? 'opacity-50 bg-accent' : ''
          }`}
      >
        <SidebarMenuSubButton
            onClick={(e) => {
              // Prevent click when dragging ends
              if (!isDragging) {
                onApiAction.open(collectionId, api.id);
              }
            }}
            className="w-full justify-start gap-2"
            asChild
        >
          <div className="w-full flex items-center gap-2 min-w-0 pr-2">
            <FileText className="h-4 w-4 flex-shrink-0"/>
            <Tooltip>
              <TooltipTrigger asChild>
                <span className="truncate flex-1">
                  {api.method && <span className="font-medium text-primary">{api.method} </span>}
                  {api.name}
                </span>
              </TooltipTrigger>
              <TooltipContent>
                <div className="flex flex-col gap-1">
                  <p className="font-medium">{api.name}</p>
                  {api.path && <p className="text-xs text-muted-foreground">{api.path}</p>}
                </div>
              </TooltipContent>
            </Tooltip>
            <SidebarMenuAction
                className="p-0 m-0 flex-shrink-0"
                onClick={(e) => e.stopPropagation()}
            >
              <ApiDropdownMenu
                  onOpen={() => onApiAction.open(collectionId, api.id)}
                  onRename={() => onApiAction.rename(collectionId, api.id)}
                  onDelete={() => onApiAction.delete(collectionId, api.id)}
              />
            </SidebarMenuAction>
          </div>
        </SidebarMenuSubButton>
      </SidebarMenuSubItem>
  );
};

export default DraggableApiItem;
