import { useState, useRef } from "react";
import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { Loader2, Trash2, Maximize2, GripVertical, X, Info } from "lucide-react";
import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import type { ProductImageSortable } from "../../types";

type SortableImage = ProductImageSortable & { url?: string };

interface SortableImageProps {
  image: SortableImage;
  productIndex: number;
  imgIndex: number;
  productName?: string; // Make this optional
  removeImage: (id: string) => void; // Changed to match ProductCard
}

// Function to ensure URLs are properly formatted with absolute paths
const getFullImageUrl = (url: string): string => {
  // If the URL is already absolute (starts with http:// or https://) return it as is
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url;
  }
  
  // Otherwise, it's a relative URL, prepend the domain
  const baseUrl = 'https://tools.acherryontop.com';
  // Make sure url starts with / for path
  const path = url.startsWith('/') ? url : `/${url}`;
  return `${baseUrl}${path}`;
};

export const SortableImage = ({ 
  image, 
  productIndex, 
  imgIndex, 
  productName,
  removeImage 
}: SortableImageProps) => {
  const [dialogOpen, setDialogOpen] = useState(false);
  const notices = image.notices ?? [];
  const attentionNotices = notices.filter((notice) => notice.level === 'warning');
  const infoNotices = notices.filter((notice) => notice.level === 'info');
  const hasAttention = attentionNotices.length > 0;
  const metadata = image.metadata;
  
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging
  } = useSortable({ 
    id: image.id,
    data: {
      productIndex,
      image,
      type: 'image'
    }
  });
  
  // Create a new style object with fixed dimensions to prevent distortion
  const style: React.CSSProperties = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
    zIndex: isDragging ? 999 : 1, // Higher z-index when dragging
    touchAction: 'none', // Prevent touch scrolling during drag 
    userSelect: 'none', // Prevent text selection during drag
    cursor: isDragging ? 'grabbing' : 'grab',
    width: '96px',
    height: '96px',
    flexShrink: 0,
    flexGrow: 0,
    position: 'relative',
  };
  
  // Create a ref for the buttons to exclude them from drag listeners
  const deleteButtonRef = useRef<HTMLButtonElement>(null);
  const zoomButtonRef = useRef<HTMLButtonElement>(null);
  
  const displayName = productName || `Product #${productIndex + 1}`;
  
  return (
    <div 
      ref={setNodeRef}
      style={style}
      className="relative border rounded-md overflow-hidden flex items-center justify-center shrink-0 cursor-grab active:cursor-grabbing select-none no-native-drag group hover:ring-2 hover:ring-primary/30 transition-all"
      {...attributes}
      {...listeners}
      onDragStart={(e) => {
        // This ensures the native drag doesn't interfere
        e.preventDefault();
        e.stopPropagation();
      }}
    >
      {image.loading ? (
        <div className="flex flex-col items-center justify-center p-2">
          <Loader2 className="h-5 w-5 animate-spin mb-1" />
          <span className="text-xs text-center truncate w-full">{image.fileName}</span>
        </div>
      ) : (
        <>
          <img 
            src={getFullImageUrl(image.url || image.imageUrl || '')} 
            alt={`${displayName} - Image ${imgIndex + 1}`}
            className="h-full w-full object-cover select-none no-native-drag"
            draggable={false}
          />
          <div className="absolute inset-0 bg-black/0 group-hover:bg-black/10 transition-colors duration-200"></div>
          <div className="absolute right-0 top-0 p-1 opacity-0 group-hover:opacity-90 transition-opacity">
            <GripVertical className="h-3 w-3 text-white drop-shadow-md" />
          </div>
          <button 
            ref={deleteButtonRef}
            className="absolute opacity-0 group-hover:opacity-100 transition-opacity duration-200 top-1 right-1 bg-black/40 hover:bg-black/70 hover:scale-110 rounded-full p-1 text-white z-10"
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation(); // Prevent triggering drag listeners
              removeImage(image.id);
            }}
            onPointerDown={(e) => {
              e.stopPropagation(); // Prevent drag from starting
            }}
            onMouseDown={(e) => {
              e.stopPropagation(); // Prevent drag from starting
            }}
            onTouchStart={(e) => {
              e.stopPropagation(); // Prevent drag from starting on touch
            }}
          >
            <Trash2 className="h-3.5 w-3.5" />
          </button>

          {hasAttention && (
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <div className="absolute bottom-1 right-1 z-10 flex items-center rounded-full bg-sky-500/90 p-1 text-white shadow-sm">
                    <Info className="h-3 w-3" />
                  </div>
                </TooltipTrigger>
                <TooltipContent side="top" align="end" className="max-w-[240px] text-xs">
                  <div className="space-y-1">
                    {attentionNotices.map((notice, idx) => (
                      <p key={`warn-${idx}`}>{notice.message}</p>
                    ))}
                    {infoNotices.map((notice, idx) => (
                      <p key={`info-${idx}`} className="text-muted-foreground">
                        {notice.message}
                      </p>
                    ))}
                    {metadata?.width && metadata?.height && (
                      <p className="text-muted-foreground">
                        Detected size: {metadata.width}×{metadata.height}
                      </p>
                    )}
                    {metadata?.optimizedSize && (
                      <p className="text-muted-foreground">
                        Optimized size: {(metadata.optimizedSize / (1024 * 1024)).toFixed(2)}MB
                      </p>
                    )}
                  </div>
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>
          )}
          
          <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
            <DialogTrigger asChild>
              <button 
                ref={zoomButtonRef}
                className="absolute opacity-0 group-hover:opacity-100 transition-opacity duration-200 bottom-1 left-1 bg-black/40 hover:bg-black/70 hover:scale-110 rounded-full p-1 text-white z-10"
                onClick={(e) => {
                  e.preventDefault();
                  e.stopPropagation(); // Prevent triggering drag listeners
                  setDialogOpen(true);
                }}
                onPointerDown={(e) => {
                  e.stopPropagation(); // Prevent drag from starting
                }}
                onMouseDown={(e) => {
                  e.stopPropagation(); // Prevent drag from starting
                }}
                onTouchStart={(e) => {
                  e.stopPropagation(); // Prevent drag from starting on touch
                }}
              >
                <Maximize2 className="h-3 w-3" />
              </button>
            </DialogTrigger>
            <DialogContent className="sm:max-w-[650px] max-h-[90vh] p-6 bg-background/95 backdrop-blur-sm border border-border rounded-lg shadow-2xl">
              <div className="relative flex flex-col items-center justify-center">
                <Button 
                  variant="ghost" 
                  size="icon" 
                  className="absolute -top-2 -right-2 bg-black/60 text-white hover:bg-black/80 rounded-full z-10 h-8 w-8"
                  onClick={() => setDialogOpen(false)}
                >
                  <X className="h-4 w-4" />
                </Button>
                <div className="overflow-hidden rounded-md border border-border shadow-md bg-white dark:bg-black">
                  <img 
                    src={getFullImageUrl(image.url || image.imageUrl || '')} 
                    alt={`${displayName} - Image ${imgIndex + 1}`}
                    className="max-h-[70vh] max-w-full object-contain"
                  />
                </div>
                <div className="mt-2 text-sm text-muted-foreground text-center">
                  {`${displayName} - Image ${imgIndex + 1}`}
                </div>
              </div>
            </DialogContent>
          </Dialog>
        </>
      )}
    </div>
  );
}; 
