"use client"

import { useState, useCallback, useRef, type DragEvent } from "react"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Progress } from "@/components/ui/progress"
import { useUpload } from "@/hooks/use-upload"
import { UploadIcon } from "lucide-react"

interface UploadDialogProps {
  onComplete?: () => void
  children?: React.ReactNode
}

export function UploadDialog({ onComplete, children }: UploadDialogProps) {
  const [open, setOpen] = useState(false)
  const [isDragging, setIsDragging] = useState(false)
  const inputRef = useRef<HTMLInputElement>(null)

  const { uploads, isUploading, upload } = useUpload(() => {
    onComplete?.()
    setOpen(false)
  })

  const handleFiles = useCallback(
    (files: FileList | null) => {
      if (!files || files.length === 0) return
      upload(Array.from(files))
    },
    [upload],
  )

  const onDrop = useCallback(
    (e: DragEvent) => {
      e.preventDefault()
      setIsDragging(false)
      handleFiles(e.dataTransfer.files)
    },
    [handleFiles],
  )

  const onDragOver = useCallback((e: DragEvent) => {
    e.preventDefault()
    setIsDragging(true)
  }, [])

  const onDragLeave = useCallback(() => setIsDragging(false), [])

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        {children ?? (
          <Button size="sm">
            <UploadIcon className="mr-2 h-4 w-4" />
            Upload
          </Button>
        )}
      </DialogTrigger>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Upload Photos</DialogTitle>
        </DialogHeader>
        <div
          onDrop={onDrop}
          onDragOver={onDragOver}
          onDragLeave={onDragLeave}
          onClick={() => inputRef.current?.click()}
          className={`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed p-8 transition-colors ${isDragging ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-muted-foreground/50"}`}
        >
          <UploadIcon className="h-8 w-8 text-muted-foreground" />
          <p className="text-sm text-muted-foreground">
            Drag & drop files here, or click to browse
          </p>
          <input
            ref={inputRef}
            type="file"
            multiple
            accept="image/*,video/*"
            className="hidden"
            onChange={(e) => handleFiles(e.target.files)}
          />
        </div>
        {uploads.length > 0 && (
          <div className="flex min-h-0 flex-col gap-2 overflow-y-auto">
            {uploads.map((u) => (
              <div key={u.file} className="flex flex-col gap-1">
                <span className="truncate text-xs">{u.file}</span>
                <Progress value={u.progress} className="h-1.5" />
              </div>
            ))}
          </div>
        )}
        {isUploading && (
          <p className="text-center text-xs text-muted-foreground">
            Uploading...
          </p>
        )}
      </DialogContent>
    </Dialog>
  )
}
