"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Upload, X, FileText, Download } from "lucide-react";
import { Button } from "./button.js";
import { Progress } from "./progress.js";
import { cn } from "../../lib/utils/index.js";
function FileUpload({
  value = [],
  onChange,
  maxFiles = 5,
  maxSize = 10,
  // 10MB default
  acceptedTypes = ["*"],
  disabled = false,
  className,
  multiple = true,
  dragDrop = 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 validateFile = (file) => {
    var _a;
    if (maxSize && file.size > maxSize * 1024 * 1024) {
      return `El archivo es muy grande. M\xE1ximo ${maxSize}MB.`;
    }
    if (acceptedTypes.length > 0 && !acceptedTypes.includes("*")) {
      const fileExtension = "." + ((_a = file.name.split(".").pop()) == null ? void 0 : _a.toLowerCase());
      const mimeType = file.type;
      const isValid = acceptedTypes.some(
        (type) => type === mimeType || type === fileExtension || type.endsWith("/*") && mimeType.startsWith(type.replace("/*", ""))
      );
      if (!isValid) {
        return `Tipo de archivo no permitido. Tipos aceptados: ${acceptedTypes.join(", ")}`;
      }
    }
    return null;
  };
  const handleFiles = (files) => {
    if (disabled) return;
    const newFiles = [];
    const errors = [];
    Array.from(files).forEach((file) => {
      if (value.length + newFiles.length >= maxFiles) {
        errors.push(`M\xE1ximo ${maxFiles} archivos permitidos`);
        return;
      }
      const error = validateFile(file);
      if (error) {
        errors.push(`${file.name}: ${error}`);
        return;
      }
      const uploadedFile = {
        id: `${Date.now()}-${Math.random()}`,
        name: file.name,
        size: file.size,
        type: file.type,
        url: URL.createObjectURL(file),
        uploadProgress: 100
        // Simulate immediate upload for demo
      };
      newFiles.push(uploadedFile);
    });
    if (errors.length > 0) {
      console.warn("File upload errors:", errors);
    }
    if (newFiles.length > 0) {
      onChange([...value, ...newFiles]);
    }
  };
  const removeFile = (fileId) => {
    if (disabled) return;
    onChange(value.filter((file) => file.id !== fileId));
  };
  const handleDragOver = (e) => {
    e.preventDefault();
    if (!disabled && dragDrop) {
      setIsDragOver(true);
    }
  };
  const handleDragLeave = (e) => {
    e.preventDefault();
    setIsDragOver(false);
  };
  const handleDrop = (e) => {
    e.preventDefault();
    setIsDragOver(false);
    if (!disabled && dragDrop && 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();
    }
  };
  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"
        ),
        onDragOver: handleDragOver,
        onDragLeave: handleDragLeave,
        onDrop: handleDrop,
        onClick: openFileDialog,
        children: [
          /* @__PURE__ */ jsx(Upload, { className: "mx-auto h-8 w-8 text-muted-foreground" }),
          /* @__PURE__ */ jsxs("p", { className: "mt-2 text-sm text-muted-foreground", children: [
            dragDrop ? "Arrastra archivos 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: [
            maxFiles > 1 ? `Hasta ${maxFiles} archivos` : "Un archivo",
            maxSize && `, m\xE1ximo ${maxSize}MB cada uno`
          ] }),
          /* @__PURE__ */ jsx(
            "input",
            {
              ref: inputRef,
              type: "file",
              multiple: multiple && maxFiles > 1,
              accept: acceptedTypes.join(","),
              onChange: handleInputChange,
              className: "absolute inset-0 w-full h-full opacity-0 cursor-pointer",
              disabled
            }
          )
        ]
      }
    ),
    value.length > 0 && /* @__PURE__ */ jsx("div", { className: "space-y-2", children: value.map((file) => /* @__PURE__ */ jsxs(
      "div",
      {
        className: "flex items-center gap-3 p-3 border rounded-lg bg-background",
        children: [
          /* @__PURE__ */ jsx(FileText, { className: "h-8 w-8 text-muted-foreground" }),
          /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0", children: [
            /* @__PURE__ */ jsx("p", { className: "text-sm font-medium truncate", children: file.name }),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: formatFileSize(file.size) }),
            file.uploadProgress !== void 0 && file.uploadProgress < 100 && /* @__PURE__ */ jsx(Progress, { value: file.uploadProgress, className: "mt-2" })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
            file.url && /* @__PURE__ */ jsx(
              Button,
              {
                variant: "ghost",
                size: "sm",
                onClick: (e) => {
                  e.stopPropagation();
                  window.open(file.url, "_blank");
                },
                children: /* @__PURE__ */ jsx(Download, { className: "h-4 w-4" })
              }
            ),
            /* @__PURE__ */ jsx(
              Button,
              {
                variant: "ghost",
                size: "sm",
                onClick: (e) => {
                  e.stopPropagation();
                  removeFile(file.id);
                },
                disabled,
                children: /* @__PURE__ */ jsx(X, { className: "h-4 w-4" })
              }
            )
          ] })
        ]
      },
      file.id
    )) })
  ] });
}
export {
  FileUpload
};
