import { useCallback, useState } from "react";
import { FileViewerModal, type ViewableFile } from "../components/FileViewer";

/**
 * Drives a single shared {@link FileViewerModal} for a page. Call `view(file)`
 * from any file row to open the document inline (pdf / image / video / office /
 * text); render `viewer` once near the page root.
 *
 *   const { view, viewer } = useFileViewer();
 *   <Button onClick={() => view({ name, url, mimeType })}>View</Button>
 *   {viewer}
 *
 * Pass `view` straight into `SmartFileInput`'s `onViewFile` prop to make its
 * already-uploaded files open in the viewer instead of a new tab.
 */
export function useFileViewer() {
  const [file, setFile] = useState<ViewableFile | null>(null);

  const view = useCallback((f: ViewableFile) => setFile(f), []);
  const close = useCallback(() => setFile(null), []);

  const viewer = (
    <FileViewerModal open={file !== null} file={file} onClose={close} />
  );

  return { view, close, viewer };
}
