"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import NextImage from "next/image";
import { X, Eye, Download, Image } from "lucide-react";
import { Button } from "./button";
import { Dialog, DialogContent, DialogTrigger } from "./dialog";
import { cn } from "../../lib/utils";
function ImageUpload({
  value = [],
  onChange,
  maxImages = 5,
  maxSize = 5,
  // 5MB default
  disabled = false,
  className,
  multiple = true,
  aspectRatio = "free",
  showPreview = true
}) {
  const [isDragOver, setIsDragOver] = React.useState(false);
  const inputRef = React.useRef(null);
  const formatFileSize = (bytes) => {
    if (bytes === 0) return "0 Bytes";
    const k = 1024;
    const sizes = ["Bytes", "KB", "MB", "GB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
  };
  const validateImage = (file) => {
    return new Promise((resolve) => {
      if (maxSize && file.size > maxSize * 1024 * 1024) {
        resolve(`La imagen es muy grande. M\xE1ximo ${maxSize}MB.`);
        return;
      }
      if (!file.type.startsWith("image/")) {
        resolve("El archivo debe ser una imagen.");
        return;
      }
      const img = document.createElement("img");
      img.onload = () => {
        resolve(null);
      };
      img.onerror = () => {
        resolve("No se pudo cargar la imagen.");
      };
      img.src = URL.createObjectURL(file);
    });
  };
  const handleFiles = async (files) => {
    if (disabled) return;
    const newImages = [];
    const errors = [];
    for (const file of Array.from(files)) {
      if (value.length + newImages.length >= maxImages) {
        errors.push(`M\xE1ximo ${maxImages} im\xE1genes permitidas`);
        break;
      }
      const error = await validateImage(file);
      if (error) {
        errors.push(`${file.name}: ${error}`);
        continue;
      }
      const uploadedImage = {
        id: `${Date.now()}-${Math.random()}`,
        name: file.name,
        size: file.size,
        url: URL.createObjectURL(file),
        alt: file.name.split(".")[0]
      };
      newImages.push(uploadedImage);
    }
    if (errors.length > 0) {
      console.warn("Image upload errors:", errors);
    }
    if (newImages.length > 0) {
      onChange([...value, ...newImages]);
    }
  };
  const removeImage = (imageId) => {
    if (disabled) return;
    onChange(value.filter((img) => img.id !== imageId));
  };
  const handleDragOver = (e) => {
    e.preventDefault();
    if (!disabled) {
      setIsDragOver(true);
    }
  };
  const handleDragLeave = (e) => {
    e.preventDefault();
    setIsDragOver(false);
  };
  const handleDrop = (e) => {
    e.preventDefault();
    setIsDragOver(false);
    if (!disabled && e.dataTransfer.files) {
      handleFiles(e.dataTransfer.files);
    }
  };
  const handleInputChange = (e) => {
    if (e.target.files) {
      handleFiles(e.target.files);
    }
  };
  const openFileDialog = () => {
    var _a;
    if (!disabled) {
      (_a = inputRef.current) == null ? void 0 : _a.click();
    }
  };
  const getAspectRatioClass = () => {
    switch (aspectRatio) {
      case "square":
        return "aspect-square";
      case "landscape":
        return "aspect-video";
      case "portrait":
        return "aspect-[3/4]";
      default:
        return "";
    }
  };
  return /* @__PURE__ */ jsxs("div", { className: cn("w-full space-y-4", className), children: [
    /* @__PURE__ */ jsxs(
      "div",
      {
        className: cn(
          "relative border-2 border-dashed rounded-lg p-6 text-center transition-colors",
          isDragOver && "border-primary bg-primary/5",
          !isDragOver && "border-muted-foreground/25",
          disabled && "opacity-50 cursor-not-allowed",
          !disabled && "cursor-pointer hover:border-primary/50",
          getAspectRatioClass()
        ),
        onDragOver: handleDragOver,
        onDragLeave: handleDragLeave,
        onDrop: handleDrop,
        onClick: openFileDialog,
        children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center h-full", children: [
            /* @__PURE__ */ jsx(Image, { className: "h-8 w-8 text-muted-foreground" }),
            /* @__PURE__ */ jsxs("p", { className: "mt-2 text-sm text-muted-foreground", children: [
              "Arrastra im\xE1genes aqu\xED o",
              " ",
              /* @__PURE__ */ jsx("span", { className: "font-medium text-primary", children: "haz clic para seleccionar" })
            ] }),
            /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground mt-1", children: [
              maxImages > 1 ? `Hasta ${maxImages} im\xE1genes` : "Una imagen",
              maxSize && `, m\xE1ximo ${maxSize}MB cada una`
            ] })
          ] }),
          /* @__PURE__ */ jsx(
            "input",
            {
              ref: inputRef,
              type: "file",
              multiple: multiple && maxImages > 1,
              accept: "image/*",
              onChange: handleInputChange,
              className: "absolute inset-0 w-full h-full opacity-0 cursor-pointer",
              disabled
            }
          )
        ]
      }
    ),
    value.length > 0 && showPreview && /* @__PURE__ */ jsx("div", { className: "grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4", children: value.map((image) => /* @__PURE__ */ jsxs(
      "div",
      {
        className: "relative group border rounded-lg overflow-hidden bg-background",
        children: [
          /* @__PURE__ */ jsxs("div", { className: cn("relative", getAspectRatioClass() || "aspect-square"), children: [
            /* @__PURE__ */ jsx(
              NextImage,
              {
                src: image.url,
                alt: image.alt || image.name,
                fill: true,
                className: "object-cover"
              }
            ),
            /* @__PURE__ */ jsxs("div", { className: "absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2", children: [
              /* @__PURE__ */ jsxs(Dialog, { children: [
                /* @__PURE__ */ jsx(DialogTrigger, { asChild: true, children: /* @__PURE__ */ jsx(Button, { variant: "secondary", size: "sm", children: /* @__PURE__ */ jsx(Eye, { className: "h-4 w-4" }) }) }),
                /* @__PURE__ */ jsx(DialogContent, { className: "max-w-3xl", children: /* @__PURE__ */ jsx(
                  NextImage,
                  {
                    src: image.url,
                    alt: image.alt || image.name,
                    width: 800,
                    height: 600,
                    className: "w-full h-auto max-h-[70vh] object-contain"
                  }
                ) })
              ] }),
              /* @__PURE__ */ jsx(
                Button,
                {
                  variant: "secondary",
                  size: "sm",
                  onClick: () => window.open(image.url, "_blank"),
                  children: /* @__PURE__ */ jsx(Download, { className: "h-4 w-4" })
                }
              ),
              /* @__PURE__ */ jsx(
                Button,
                {
                  variant: "destructive",
                  size: "sm",
                  onClick: () => removeImage(image.id),
                  disabled,
                  children: /* @__PURE__ */ jsx(X, { className: "h-4 w-4" })
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "p-2", children: [
            /* @__PURE__ */ jsx("p", { className: "text-xs font-medium truncate", children: image.name }),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: formatFileSize(image.size) })
          ] })
        ]
      },
      image.id
    )) })
  ] });
}
export {
  ImageUpload
};
