"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import NextImage from "next/image";
import { X, Play, Download, Video } from "lucide-react";
import { Button } from "./button";
import { cn } from "../../lib/utils";
function VideoUpload({
  value = [],
  onChange,
  maxVideos = 3,
  maxSize = 100,
  // 100MB default
  disabled = false,
  className,
  multiple = true,
  acceptedFormats = ["mp4", "mov", "avi", "mkv", "webm"]
}) {
  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 formatDuration = (seconds) => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs.toString().padStart(2, "0")}`;
  };
  const validateVideo = (file) => {
    return new Promise((resolve) => {
      var _a;
      if (maxSize && file.size > maxSize * 1024 * 1024) {
        resolve(`El video es muy grande. M\xE1ximo ${maxSize}MB.`);
        return;
      }
      if (!file.type.startsWith("video/")) {
        resolve("El archivo debe ser un video.");
        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 generateThumbnail = (file) => {
    return new Promise((resolve) => {
      const video = document.createElement("video");
      video.preload = "metadata";
      video.onloadedmetadata = () => {
        video.currentTime = video.duration / 2;
      };
      video.onseeked = () => {
        const canvas = document.createElement("canvas");
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        const ctx = canvas.getContext("2d");
        ctx == null ? void 0 : ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        resolve(canvas.toDataURL());
      };
      video.onerror = () => {
        resolve("");
      };
      video.src = URL.createObjectURL(file);
    });
  };
  const handleFiles = async (files) => {
    if (disabled) return;
    const newVideos = [];
    const errors = [];
    for (const file of Array.from(files)) {
      if (value.length + newVideos.length >= maxVideos) {
        errors.push(`M\xE1ximo ${maxVideos} videos permitidos`);
        break;
      }
      const error = await validateVideo(file);
      if (error) {
        errors.push(`${file.name}: ${error}`);
        continue;
      }
      const thumbnail = await generateThumbnail(file);
      const uploadedVideo = {
        id: `${Date.now()}-${Math.random()}`,
        name: file.name,
        size: file.size,
        url: URL.createObjectURL(file),
        thumbnail
      };
      newVideos.push(uploadedVideo);
    }
    if (errors.length > 0) {
      console.warn("Video upload errors:", errors);
    }
    if (newVideos.length > 0) {
      onChange([...value, ...newVideos]);
    }
  };
  const removeVideo = (videoId) => {
    if (disabled) return;
    onChange(value.filter((video) => video.id !== videoId));
  };
  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(Video, { className: "mx-auto h-8 w-8 text-muted-foreground" }),
          /* @__PURE__ */ jsxs("p", { className: "mt-2 text-sm text-muted-foreground", children: [
            "Arrastra videos 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: [
            maxVideos > 1 ? `Hasta ${maxVideos} videos` : "Un video",
            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 && maxVideos > 1,
              accept: "video/*",
              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((video) => /* @__PURE__ */ jsxs(
      "div",
      {
        className: "flex items-center gap-4 p-4 border rounded-lg bg-background",
        children: [
          /* @__PURE__ */ jsxs("div", { className: "relative w-24 h-16 bg-muted rounded overflow-hidden", children: [
            video.thumbnail ? /* @__PURE__ */ jsx(
              NextImage,
              {
                src: video.thumbnail,
                alt: video.name,
                fill: true,
                className: "object-cover"
              }
            ) : /* @__PURE__ */ jsx("div", { className: "w-full h-full flex items-center justify-center", children: /* @__PURE__ */ jsx(Video, { className: "h-6 w-6 text-muted-foreground" }) }),
            /* @__PURE__ */ jsx("div", { className: "absolute inset-0 flex items-center justify-center bg-black/30", children: /* @__PURE__ */ jsx(Play, { className: "h-4 w-4 text-white" }) })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0", children: [
            /* @__PURE__ */ jsx("p", { className: "text-sm font-medium truncate", children: video.name }),
            /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
              formatFileSize(video.size),
              video.duration && ` \u2022 ${formatDuration(video.duration)}`
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsx(
              Button,
              {
                variant: "ghost",
                size: "sm",
                onClick: () => window.open(video.url, "_blank"),
                children: /* @__PURE__ */ jsx(Download, { className: "h-4 w-4" })
              }
            ),
            /* @__PURE__ */ jsx(
              Button,
              {
                variant: "ghost",
                size: "sm",
                onClick: () => removeVideo(video.id),
                disabled,
                children: /* @__PURE__ */ jsx(X, { className: "h-4 w-4" })
              }
            )
          ] })
        ]
      },
      video.id
    )) })
  ] });
}
export {
  VideoUpload
};
