"use client"

import { useQuery } from "@tanstack/react-query"
import {
  fetchPublicShareBlob,
  publicSharePreviewApiPath,
} from "@/lib/api/public-share"
import { blobForPreview } from "@/lib/api/drive-download"
import { commitPreviewBlobUrl } from "@/lib/api/preview-blob-url"
import type { DriveFileInfo } from "@/lib/api/types"
import { drivePreviewKind, driveServerThumbnail } from "@/lib/drive/drive-preview"
import type { DrivePreviewThumb, DriveThumbDisplay } from "@/lib/api/hooks/use-drive-preview-thumb"

export type PublicShareThumbContext = {
  token: string
  password?: string
}

export function usePublicSharePreviewThumb(
  file: DriveFileInfo,
  publicShare: PublicShareThumbContext | undefined,
  enabled: boolean
) {
  const clientKind = drivePreviewKind(file)
  const canPreview =
    Boolean(publicShare) &&
    file.type === "file" &&
    clientKind !== "audio" &&
    (driveServerThumbnail(file) || clientKind !== null)

  return useQuery({
    queryKey: ["public-share", "preview-thumb", publicShare?.token, file.path, file.etag],
    enabled: Boolean(publicShare) && enabled && canPreview,
    queryFn: async ({ client, queryKey }): Promise<DrivePreviewThumb> => {
      if (!publicShare) throw new Error("preview unavailable")
      const previous = client.getQueryData<DrivePreviewThumb>(queryKey)

      if (driveServerThumbnail(file)) {
        const res = await fetch(
          publicSharePreviewApiPath(publicShare.token, file, publicShare.password)
        )
        if (res.ok) {
          const raw = await res.blob()
          const blob = blobForPreview(raw, file.mime_type ?? "", file.name)
          return commitPreviewBlobUrl(previous, {
            url: URL.createObjectURL(blob),
            display: "image" as DriveThumbDisplay,
          })
        }
      }

      if (!clientKind || clientKind === "audio") {
        throw new Error("preview unavailable")
      }

      const raw = await fetchPublicShareBlob(publicShare.token, file, publicShare.password)
      const blob = blobForPreview(raw, file.mime_type ?? "", file.name)
      return commitPreviewBlobUrl(previous, {
        url: URL.createObjectURL(blob),
        display: clientKind === "video" ? "video" : "image",
      })
    },
    staleTime: 5 * 60_000,
    gcTime: 10 * 60_000,
    retry: 1,
  })
}
