"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { X, Play, Pause, Download, Music } from "lucide-react";
import { Button } from "./button";
import { Progress } from "./progress";
import { cn } from "../../lib/utils";
function AudioUpload({
  value = [],
  onChange,
  maxAudios = 5,
  maxSize = 50,
  // 50MB default
  disabled = false,
  className,
  multiple = true,
  acceptedFormats = ["mp3", "wav", "ogg", "m4a", "aac"],
  showPlayer = true
}) {
  const [isDragOver, setIsDragOver] = React.useState(false);
  const [playingId, setPlayingId] = React.useState(null);
  const [progress, setProgress] = React.useState({});
  const inputRef = React.useRef(null);
  const audioRefs = React.useRef({});
  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 formatDuration = (seconds) => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs.toString().padStart(2, "0")}`;
  };
  const validateAudio = (file) => {
    return new Promise((resolve) => {
      var _a;
      if (maxSize && file.size > maxSize * 1024 * 1024) {
        resolve(`El audio es muy grande. M\xE1ximo ${maxSize}MB.`);
        return;
      }
      if (!file.type.startsWith("audio/")) {
        resolve("El archivo debe ser un audio.");
        return;
      }
      const fileExtension = (_a = file.name.split(".").pop()) == null ? void 0 : _a.toLowerCase();
      if (fileExtension && !acceptedFormats.includes(fileExtension)) {
        resolve(`Formato no soportado. Formatos aceptados: ${acceptedFormats.join(", ")}`);
        return;
      }
      resolve(null);
    });
  };
  const getAudioDuration = (file) => {
    return new Promise((resolve) => {
      const audio = document.createElement("audio");
      audio.preload = "metadata";
      audio.onloadedmetadata = () => {
        resolve(audio.duration);
      };
      audio.onerror = () => {
        resolve(void 0);
      };
      audio.src = URL.createObjectURL(file);
    });
  };
  const handleFiles = async (files) => {
    if (disabled) return;
    const newAudios = [];
    const errors = [];
    for (const file of Array.from(files)) {
      if (value.length + newAudios.length >= maxAudios) {
        errors.push(`M\xE1ximo ${maxAudios} audios permitidos`);
        break;
      }
      const error = await validateAudio(file);
      if (error) {
        errors.push(`${file.name}: ${error}`);
        continue;
      }
      const duration = await getAudioDuration(file);
      const uploadedAudio = {
        id: `${Date.now()}-${Math.random()}`,
        name: file.name,
        size: file.size,
        url: URL.createObjectURL(file),
        duration
      };
      newAudios.push(uploadedAudio);
    }
    if (errors.length > 0) {
      console.warn("Audio upload errors:", errors);
    }
    if (newAudios.length > 0) {
      onChange([...value, ...newAudios]);
    }
  };
  const removeAudio = (audioId) => {
    if (disabled) return;
    if (playingId === audioId) {
      setPlayingId(null);
    }
    if (audioRefs.current[audioId]) {
      delete audioRefs.current[audioId];
    }
    onChange(value.filter((audio) => audio.id !== audioId));
  };
  const togglePlay = (audio) => {
    var _a;
    if (!showPlayer) return;
    if (playingId === audio.id) {
      (_a = audioRefs.current[audio.id]) == null ? void 0 : _a.pause();
      setPlayingId(null);
    } else {
      if (playingId && audioRefs.current[playingId]) {
        audioRefs.current[playingId].pause();
      }
      if (!audioRefs.current[audio.id]) {
        const audioElement = new Audio(audio.url);
        audioRefs.current[audio.id] = audioElement;
        audioElement.addEventListener("timeupdate", () => {
          if (audioElement.duration) {
            const progressPercent = audioElement.currentTime / audioElement.duration * 100;
            setProgress((prev) => ({ ...prev, [audio.id]: progressPercent }));
          }
        });
        audioElement.addEventListener("ended", () => {
          setPlayingId(null);
          setProgress((prev) => ({ ...prev, [audio.id]: 0 }));
        });
      }
      audioRefs.current[audio.id].play();
      setPlayingId(audio.id);
    }
  };
  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();
    }
  };
  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(Music, { className: "mx-auto h-8 w-8 text-muted-foreground" }),
          /* @__PURE__ */ jsxs("p", { className: "mt-2 text-sm text-muted-foreground", children: [
            "Arrastra audios 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: [
            maxAudios > 1 ? `Hasta ${maxAudios} audios` : "Un audio",
            maxSize && `, m\xE1ximo ${maxSize}MB cada uno`
          ] }),
          /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
            "Formatos: ",
            acceptedFormats.join(", ")
          ] }),
          /* @__PURE__ */ jsx(
            "input",
            {
              ref: inputRef,
              type: "file",
              multiple: multiple && maxAudios > 1,
              accept: "audio/*",
              onChange: handleInputChange,
              className: "absolute inset-0 w-full h-full opacity-0 cursor-pointer",
              disabled
            }
          )
        ]
      }
    ),
    value.length > 0 && /* @__PURE__ */ jsx("div", { className: "space-y-4", children: value.map((audio) => /* @__PURE__ */ jsxs(
      "div",
      {
        className: "flex items-center gap-4 p-4 border rounded-lg bg-background",
        children: [
          showPlayer && /* @__PURE__ */ jsx(
            Button,
            {
              variant: "ghost",
              size: "sm",
              onClick: () => togglePlay(audio),
              className: "flex-shrink-0",
              children: playingId === audio.id ? /* @__PURE__ */ jsx(Pause, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Play, { className: "h-4 w-4" })
            }
          ),
          !showPlayer && /* @__PURE__ */ jsx("div", { className: "w-10 h-10 rounded bg-muted flex items-center justify-center flex-shrink-0", children: /* @__PURE__ */ jsx(Music, { className: "h-5 w-5 text-muted-foreground" }) }),
          /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0", children: [
            /* @__PURE__ */ jsx("p", { className: "text-sm font-medium truncate", children: audio.name }),
            /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground mb-2", children: [
              formatFileSize(audio.size),
              audio.duration && ` \u2022 ${formatDuration(audio.duration)}`
            ] }),
            showPlayer && playingId === audio.id && /* @__PURE__ */ jsx(
              Progress,
              {
                value: progress[audio.id] || 0,
                className: "h-1"
              }
            )
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 flex-shrink-0", children: [
            /* @__PURE__ */ jsx(
              Button,
              {
                variant: "ghost",
                size: "sm",
                onClick: () => window.open(audio.url, "_blank"),
                children: /* @__PURE__ */ jsx(Download, { className: "h-4 w-4" })
              }
            ),
            /* @__PURE__ */ jsx(
              Button,
              {
                variant: "ghost",
                size: "sm",
                onClick: () => removeAudio(audio.id),
                disabled,
                children: /* @__PURE__ */ jsx(X, { className: "h-4 w-4" })
              }
            )
          ] })
        ]
      },
      audio.id
    )) })
  ] });
}
export {
  AudioUpload
};
