import type * as React from 'react'
import { Button } from '@admin/components/ui/button'
import { Card, CardContent, CardFooter } from '@admin/components/ui/card'
import { Skeleton } from '@admin/components/ui/skeleton'
import { useSortable } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { GripVertical } from 'lucide-react'

export function SortableGalleryItem({
  id,
  disabled,
  children
}: {
  id: string
  disabled?: boolean
  children: React.ReactNode
}) {
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
    id,
    disabled
  })

  return (
    <div
      ref={setNodeRef}
      data-gallery-dragging={isDragging ? 'true' : undefined}
      style={{
        transform: CSS.Translate.toString(transform),
        transition: isDragging ? undefined : transition,
        zIndex: isDragging ? 30 : undefined,
        willChange: isDragging ? 'transform' : undefined
      }}
      className="group relative min-w-0 select-none [&[data-gallery-dragging=true]_[data-gallery-drag-handle]]:pointer-events-none [&[data-gallery-dragging=true]_[data-gallery-drag-handle]]:opacity-0 [&[data-gallery-dragging=true]_[data-media-field-action]]:pointer-events-none [&[data-gallery-dragging=true]_[data-media-field-action]]:opacity-0"
    >
      <div
        aria-hidden="true"
        className="pointer-events-none absolute inset-0 opacity-0 transition-opacity group-data-[gallery-dragging=true]:opacity-100"
      >
        <Card className="h-full">
          <CardContent className="flex flex-col p-2">
            <div className="flex aspect-square size-full overflow-hidden rounded-sm border border-border bg-background">
              <Skeleton className="size-full" />
            </div>
          </CardContent>
          <CardFooter>
            <Skeleton className="h-4 w-3/4" />
          </CardFooter>
        </Card>
      </div>
      {!disabled && (
        <Button
          {...attributes}
          {...listeners}
          data-gallery-drag-handle
          variant="outline"
          size="icon-sm"
          className="absolute top-1 right-1 z-10 cursor-grab touch-none border-primary/10 opacity-0 transition-[opacity,transform] group-hover:opacity-100 active:scale-[0.96] active:cursor-grabbing"
        >
          <GripVertical className="size-3.5 text-foreground" />
        </Button>
      )}

      <div className="relative transition-opacity group-data-[gallery-dragging=true]:opacity-0">
        {children}
      </div>
    </div>
  )
}
