"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState, useRef, useEffect, useCallback } from "react";
import { useTranslations } from "next-intl";
import { XIcon } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from "../ui/dialog.js";
import { Button } from "../ui/button.js";
import { MediaToolbar } from "./MediaToolbar.js";
import { MediaGrid } from "./MediaGrid.js";
import { MediaList } from "./MediaList.js";
import { MediaUploadZone } from "./MediaUploadZone.js";
import { MediaTagFilter } from "./MediaTagFilter.js";
import { useMediaList } from "../../hooks/useMedia.js";
import { useDebounce } from "../../hooks/useDebounce.js";
import { useToast } from "../../hooks/useToast.js";
import { sel } from "../../lib/selectors/index.js";
function MediaLibrary({
  isOpen,
  onClose,
  onSelect,
  mode = "single",
  allowedTypes,
  maxSelections
}) {
  const t = useTranslations("media");
  const { toast } = useToast();
  const [viewMode, setViewMode] = useState("grid");
  const [searchQuery, setSearchQuery] = useState("");
  const [typeFilter, setTypeFilter] = useState("all");
  const [sortBy, setSortBy] = useState("createdAt");
  const [sortDir, setSortDir] = useState("desc");
  const [selectedIds, setSelectedIds] = useState(/* @__PURE__ */ new Set());
  const [selectedTagIds, setSelectedTagIds] = useState([]);
  const [showUploadZone, setShowUploadZone] = useState(false);
  const lastSelectedIndexRef = useRef(null);
  const debouncedSearch = useDebounce(searchQuery, 300);
  const { data, isLoading, refetch } = useMediaList({
    limit: 100,
    offset: 0,
    orderBy: sortBy,
    orderDir: sortDir,
    type: typeFilter,
    search: debouncedSearch || void 0,
    tagIds: selectedTagIds.length > 0 ? selectedTagIds : void 0
  });
  const items = (data == null ? void 0 : data.data) || [];
  useEffect(() => {
    if (!isOpen) {
      setSelectedIds(/* @__PURE__ */ new Set());
      setSelectedTagIds([]);
      setShowUploadZone(false);
      lastSelectedIndexRef.current = null;
    }
  }, [isOpen]);
  const handleSelect = useCallback((media, options) => {
    if (mode === "single") {
      setSelectedIds(/* @__PURE__ */ new Set([media.id]));
    } else {
      const currentIndex = items.findIndex((m) => m.id === media.id);
      if ((options == null ? void 0 : options.shiftKey) && lastSelectedIndexRef.current !== null && currentIndex !== -1) {
        const start = Math.min(lastSelectedIndexRef.current, currentIndex);
        const end = Math.max(lastSelectedIndexRef.current, currentIndex);
        const rangeIds = items.slice(start, end + 1).map((m) => m.id);
        setSelectedIds((prev) => {
          const newSet = new Set(prev);
          for (const id of rangeIds) {
            if (maxSelections && newSet.size >= maxSelections) {
              toast({
                title: t("upload.error"),
                description: t("upload.maxSelectionsReached", { maxSelections }),
                variant: "destructive"
              });
              break;
            }
            newSet.add(id);
          }
          return newSet;
        });
      } else {
        setSelectedIds((prev) => {
          const newSet = new Set(prev);
          if (newSet.has(media.id)) {
            newSet.delete(media.id);
          } else {
            if (maxSelections && newSet.size >= maxSelections) {
              toast({
                title: t("upload.error"),
                description: t("upload.maxSelectionsReached", { maxSelections }),
                variant: "destructive"
              });
              return prev;
            }
            newSet.add(media.id);
          }
          return newSet;
        });
      }
      lastSelectedIndexRef.current = currentIndex;
    }
  }, [mode, maxSelections, toast, t, items]);
  const handleConfirmSelection = () => {
    if (selectedIds.size === 0) return;
    const selectedMedia = items.filter((m) => selectedIds.has(m.id));
    if (selectedMedia.length === 0) return;
    if (mode === "single") {
      onSelect == null ? void 0 : onSelect(selectedMedia[0]);
    } else {
      onSelect == null ? void 0 : onSelect(selectedMedia);
    }
    onClose();
  };
  const handleUploadComplete = useCallback(() => {
    setShowUploadZone(false);
    refetch();
  }, [refetch]);
  const handleSortChange = useCallback((orderBy, orderDir) => {
    setSortBy(orderBy);
    setSortDir(orderDir);
  }, []);
  const handleToggleUpload = useCallback(() => {
    setShowUploadZone((prev) => !prev);
  }, []);
  const selectedCount = selectedIds.size;
  const canSelect = selectedCount > 0;
  return /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsx(Dialog, { open: isOpen, onOpenChange: (open) => !open && onClose(), children: /* @__PURE__ */ jsxs(
    DialogContent,
    {
      "data-cy": sel("media.library.dialog"),
      className: "sm:max-w-[90vw] lg:max-w-6xl h-[90vh] overflow-hidden flex flex-col",
      showCloseButton: false,
      children: [
        /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(DialogTitle, { "data-cy": sel("media.library.title"), children: t("title") }),
            /* @__PURE__ */ jsx(DialogDescription, { children: t("subtitle") })
          ] }),
          /* @__PURE__ */ jsx(
            Button,
            {
              "data-cy": sel("media.library.closeBtn"),
              variant: "ghost",
              size: "icon",
              onClick: onClose,
              "aria-label": t("actions.cancel"),
              children: /* @__PURE__ */ jsx(XIcon, { className: "h-4 w-4" })
            }
          )
        ] }) }),
        /* @__PURE__ */ jsxs("div", { className: "flex-1 min-h-0 overflow-y-auto space-y-4 p-1 -m-1", children: [
          /* @__PURE__ */ jsx(
            MediaToolbar,
            {
              onUploadClick: handleToggleUpload,
              searchQuery,
              onSearchChange: setSearchQuery,
              typeFilter,
              onTypeFilterChange: setTypeFilter,
              sortBy,
              sortDir,
              onSortChange: handleSortChange,
              viewMode,
              onViewModeChange: setViewMode
            }
          ),
          /* @__PURE__ */ jsx(
            MediaTagFilter,
            {
              selectedTagIds,
              onTagsChange: setSelectedTagIds
            }
          ),
          showUploadZone && /* @__PURE__ */ jsx(MediaUploadZone, { onUploadComplete: handleUploadComplete }),
          viewMode === "grid" ? /* @__PURE__ */ jsx(
            MediaGrid,
            {
              items,
              isLoading,
              selectedIds,
              onSelect: handleSelect,
              mode
            }
          ) : /* @__PURE__ */ jsx(
            MediaList,
            {
              items,
              isLoading,
              selectedIds,
              onSelect: handleSelect,
              mode
            }
          )
        ] }),
        /* @__PURE__ */ jsx(DialogFooter, { "data-cy": sel("media.footer.container"), children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between w-full", children: [
          /* @__PURE__ */ jsx("div", { "data-cy": sel("media.footer.selectionCount"), children: selectedCount > 0 && /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: selectedCount === 1 ? t("footer.itemsSelected", { count: selectedCount }) : t("footer.itemsSelectedPlural", { count: selectedCount }) }) }),
          /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
            /* @__PURE__ */ jsx(
              Button,
              {
                "data-cy": sel("media.footer.cancelBtn"),
                variant: "outline",
                onClick: onClose,
                children: t("footer.cancel")
              }
            ),
            /* @__PURE__ */ jsx(
              Button,
              {
                "data-cy": sel("media.footer.selectBtn"),
                onClick: handleConfirmSelection,
                disabled: !canSelect,
                children: t("footer.select")
              }
            )
          ] })
        ] }) })
      ]
    }
  ) }) });
}
export {
  MediaLibrary
};
