import { jsxs as Q, jsx as w } from "react/jsx-runtime";
import { useState as V, useMemo as U, useCallback as l } from "react";
import { useDropzone as X } from "react-dropzone";
import c from "./types/FileStatus.js";
import $ from "../../utils/generateCustomID.js";
import Y from "./components/DropZone.js";
import _ from "./components/File.js";
import h from "../error-message/ErrorMessage.js";
import { c as T } from "../../index-BtlgVD4m.js";
const le = ({
  maxSize: L = 5,
  allowMultiple: g = !1,
  acceptedFileType: p,
  value: R,
  errorMessage: z,
  onChange: o,
  onRemove: m,
  onDownload: v,
  onUpload: j,
  onError: b,
  isError: K = !1
}) => {
  const [M, d] = V([]), A = R !== void 0, n = A ? R : M, E = U(() => L * 1024 * 1024, [L]), B = U(
    () => n.reduce(
      (e, s) => (s.status === c.Success && e.success++, s.status === c.Error && e.error++, s.status === c.Uploading && e.uploading++, e),
      { success: 0, error: 0, uploading: 0 }
    ),
    [n]
  ), I = l(
    (e, s) => {
      d((t) => {
        const i = t.map((r) => r.id === e ? { ...r, status: c.Uploading, progress: s } : r);
        return o == null || o({ newFiles: [], fileList: i }), i;
      });
    },
    [o]
  ), k = l(
    (e, s) => {
      d((t) => {
        const i = t.map(
          (r) => r.id === e ? {
            ...r,
            url: s || (r.file ? URL.createObjectURL(r.file) : void 0),
            status: c.Success,
            progress: 100
          } : r
        );
        return o == null || o({ newFiles: [], fileList: i }), i;
      });
    },
    [o]
  ), S = l(
    (e, s) => {
      d((t) => {
        const i = t.map(
          (r) => r.id === e ? {
            ...r,
            status: c.Error,
            progress: 100,
            error: {
              code: "Upload failed",
              message: s instanceof Error ? s.message : "Something bad happened please try again"
            }
          } : r
        );
        return o == null || o({ newFiles: [], fileList: i }), i;
      });
    },
    [o]
  ), x = l(
    (e) => (s) => {
      d((t) => {
        const i = t.map((r) => r.id === e ? { ...r, status: c.Uploading, progress: s } : r);
        return o == null || o({ newFiles: [], fileList: i }), i;
      });
    },
    [o]
  ), N = l(
    async (e) => {
      try {
        if (j) {
          const s = await j(e, x(e.id));
          k((s == null ? void 0 : s.id) || e.id, s == null ? void 0 : s.url);
        } else {
          for (let s = 0; s <= 100; s += 10)
            await new Promise((t) => setTimeout(t, 100)), I(e.id, s);
          await new Promise((s) => setTimeout(s, 500)), k(e.id);
        }
      } catch (s) {
        S(e.id, s);
      }
    },
    [I, k, S, j, x]
  ), W = l(
    (e) => {
      d((s) => s.filter((t) => t.id !== e.id)), m == null || m(e);
    },
    [m]
  ), F = U(() => {
    if (!p) return;
    if (typeof p == "object") return p;
    const e = p.split(",").map((s) => s.trim()).filter(Boolean).map((s) => s.startsWith(".") ? s : `.${s}`);
    return e.length ? { "": e } : void 0;
  }, [p]), y = U(() => F ? Object.values(F).flat().join(", ") : "", [F]), Z = l(
    (e, s) => {
      const t = e.map((a) => ({
        id: $("file"),
        name: a.name,
        size: a.size,
        status: c.Uploading,
        file: a
      })), i = s.map(({ file: a, errors: P }) => {
        const f = P[0];
        let u = f;
        return f.code === "file-too-large" ? u = {
          code: "exceeds file size limit",
          message: `Please upload a file smaller than ${L}MB.`
        } : f.code === "file-invalid-type" && (u = {
          code: "unsupported file type",
          message: y ? `Please upload one of: ${y}.` : "This file type is not supported."
        }), b == null || b({ file: a, code: f.code, message: (u == null ? void 0 : u.message) ?? f.message }), {
          id: $("file"),
          name: a.name,
          size: a.size,
          status: c.Error,
          error: u
        };
      }), r = [...n, ...t, ...i];
      d(r), t.forEach((a) => N(a));
    },
    [L, n, N, y, b]
  ), { getRootProps: q, getInputProps: G, isDragActive: H } = X({
    // Enables opening file dialog when clicking the dropzone
    noClick: !1,
    // Disables opening file dialog when pressing enter
    noKeyboard: !0,
    // Indicates that user can upload multiple files at once.
    multiple: g,
    // Maximum size of the file in bytes.
    maxSize: E,
    // Restrict selectable file types — invalid picks (including drag-drop and OS "All files" override) are routed to rejectedFiles.
    accept: F,
    // The function that will be called when the user drops files into the dropzone.
    onDrop: Z,
    // Prevents the dropzone from being disabled when the user is uploading files.
    disabled: !g && B.uploading > 0
  }), D = l((e, s) => {
    const t = document.createElement("a");
    t.href = e, t.download = s, t.dispatchEvent(new MouseEvent("click")), setTimeout(() => {
      URL.revokeObjectURL(e);
    }, 100);
  }, []), J = l(
    async (e) => {
      v ? v(e) : (async () => {
        if (e.file) {
          const t = URL.createObjectURL(e.file);
          D(t, e.name);
          return;
        } else if (e.url)
          try {
            const t = await fetch(e.url);
            if (!t.ok)
              throw new Error("Network response was not ok");
            const i = await t.blob(), r = new FileReader();
            r.onload = () => {
              const a = r.result;
              if (a) {
                const P = URL.createObjectURL(new Blob([a]));
                D(P, e.name);
              }
            }, r.readAsArrayBuffer(i);
          } catch (t) {
            console.error("Error downloading file:", t);
          }
      })();
    },
    [v, D]
  );
  return /* @__PURE__ */ Q(
    "div",
    {
      className: T(
        "relative flex flex-col gap-[var(--spacing-3)] w-[500px] max-w-full",
        K && "ring-1 ring-[var(--base-ring-error)] ring-offset-2 rounded-md"
      ),
      children: [
        /* @__PURE__ */ w("input", { ...G({ role: "textbox" }) }),
        (g || B.success < 1) && /* @__PURE__ */ w(Y, { ...q({ isDragActive: H, maxSize: E, errorMessage: z }) }),
        !!n.length && /* @__PURE__ */ w("div", { className: "flex flex-col gap-[var(--spacing-3)]", children: n.map((e) => /* @__PURE__ */ w(_, { file: e, onRemove: A ? m : W, onDownload: J }, e.id)) }),
        /* @__PURE__ */ w(h, { message: z })
      ]
    }
  );
};
export {
  le as default
};
//# sourceMappingURL=FileUpload.js.map
