"use client";
import { useEffect, useMemo, useState } from "react";
import {
ChevronRight,
Database,
FileText,
Folder,
RefreshCw,
} from "lucide-react";
import { Checkbox } from "@/components/ui/checkbox";
import { EmptyState } from "@/components/ui/empty-state";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useOssList } from "@/hooks/use-oss-list";
import { formatErrorContext } from "@/lib/api-error-toast";
import {
isFileSelected,
isFolderSelected,
toggleFile,
toggleFolder,
type OssSelection,
} from "@/lib/oss-selection";
import { cn } from "@/lib/utils";
import { useI18n } from "@/i18n/i18n-context";
interface OssBrowserProps {
selection: OssSelection;
onSelectionChange: (next: OssSelection) => void;
}
const SEARCH_DEBOUNCE_MS = 250;
/** Format a byte count as "1.2 MB" / "344 KB" / "12 B" with one decimal. */
function formatBytes(n: number): string {
if (!Number.isFinite(n) || n <= 0) return "—";
const units = ["B", "KB", "MB", "GB"];
let i = 0;
let v = n;
while (v >= 1024 && i < units.length - 1) {
v /= 1024;
i++;
}
return `${v.toFixed(i === 0 ? 0 : 1)} ${units[i]}`;
}
/** Slice a prefix into breadcrumb segments. "" → [], "docs/2026/" → [docs, 2026]. */
function breadcrumbSegments(
prefix: string,
): { label: string; prefix: string }[] {
if (!prefix) return [];
const trimmed = prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
const parts = trimmed.split("/");
const out: { label: string; prefix: string }[] = [];
let acc = "";
for (const p of parts) {
acc += `${p}/`;
out.push({ label: p, prefix: acc });
}
return out;
}
/**
* Single-level OSS file/folder picker. The component owns navigation
* (`prefix`, `search`) and lifts selection up; the parent decides how the
* selection turns into a submission.
*
* Empty / error states render inline so a misconfigured OSS doesn't kick
* the user out of the upload dialog — they can switch back to a local tab.
*/
export function OssBrowser({ selection, onSelectionChange }: OssBrowserProps) {
const { t } = useI18n();
const [prefix, setPrefix] = useState("");
const [searchInput, setSearchInput] = useState("");
const [search, setSearch] = useState("");
// Debounce search to keep keystrokes off the wire.
useEffect(() => {
const id = setTimeout(
() => setSearch(searchInput.trim()),
SEARCH_DEBOUNCE_MS,
);
return () => clearTimeout(id);
}, [searchInput]);
const {
folders,
files,
isLoading,
isFetchingNextPage,
hasNextPage,
fetchNextPage,
refetch,
error,
apiError,
errorCode,
} = useOssList({ prefix, search });
const breadcrumbs = useMemo(() => breadcrumbSegments(prefix), [prefix]);
// ---------- Empty / error branches ----------
if (errorCode === "OSS_NOT_CONFIGURED") {
return (