"use client"

import { useMemo } from "react"
import { useQuery } from "@tanstack/react-query"
import { apiClient } from "@/lib/api/client"
import { blobForPreview } from "@/lib/api/drive-download"
import { commitPreviewBlobUrl } from "@/lib/api/preview-blob-url"
import type { PreviewBlobThumb } from "@/lib/api/preview-blob-url"
import { useDrivePreviewThumb } from "@/lib/api/hooks/use-drive-preview-thumb"
import { useAuthReady } from "@/lib/api/use-auth-ready"
import type { DriveFileInfo } from "@/lib/api/types"
import type { EmailAttachment } from "@/lib/email-data"
import { guessMailAttachmentMime } from "@/lib/mail/mail-attachment-preview"
import { drivePreviewKind, driveServerThumbnail } from "@/lib/drive/drive-preview"

const MAX_THUMB_BYTES = 15 * 1024 * 1024

function mailAttachmentCanThumb(att: EmailAttachment): boolean {
  if (!att.id) return false
  if (att.sizeBytes !== undefined && att.sizeBytes > MAX_THUMB_BYTES) return false
  const mime = guessMailAttachmentMime(att.name, att.contentType)
  const kind = drivePreviewKind({ name: att.name, mime_type: mime })
  if (!kind || kind === "audio" || kind === "text") return false
  if (kind === "pdf") return true
  return kind === "image" || kind === "video"
}

function useMailBlobAttachmentThumb(att: EmailAttachment, enabled: boolean) {
  const { ready, authenticated } = useAuthReady()
  const mime = guessMailAttachmentMime(att.name, att.contentType)
  const kind = drivePreviewKind({ name: att.name, mime_type: mime })

  return useQuery({
    queryKey: ["mail", "attachment-thumb", att.id, att.name, att.sizeBytes],
    enabled: ready && authenticated && enabled && mailAttachmentCanThumb(att),
    queryFn: async ({ client, queryKey }): Promise<PreviewBlobThumb> => {
      const previous = client.getQueryData<PreviewBlobThumb>(queryKey)
      const raw = await apiClient.getBlob(`/mail/attachments/${att.id}`)
      const blob = blobForPreview(raw, mime, att.name)

      if (kind === "pdf") {
        const { renderMailPdfThumb } = await import("@/lib/mail/mail-pdf-thumb")
        const url = await renderMailPdfThumb(blob)
        return commitPreviewBlobUrl(previous, { url, display: "image" })
      }

      return commitPreviewBlobUrl(previous, {
        url: URL.createObjectURL(blob),
        display: kind === "video" ? "video" : "image",
      })
    },
    staleTime: 5 * 60_000,
    gcTime: 10 * 60_000,
    retry: 1,
  })
}

export function useMailAttachmentThumb(att: EmailAttachment, enabled: boolean) {
  const mime = guessMailAttachmentMime(att.name, att.contentType)
  const driveFile = useMemo(
    (): DriveFileInfo => ({
      path: att.drivePath ?? "/",
      name: att.name,
      type: "file",
      size: att.sizeBytes ?? 0,
      mime_type: mime,
      last_modified: "",
      etag: att.id ?? att.name,
      is_favorite: false,
    }),
    [att.drivePath, att.name, att.sizeBytes, att.id, mime]
  )

  const useDrive =
    Boolean(att.drivePath) &&
    mailAttachmentCanThumb(att) &&
    (driveServerThumbnail(driveFile) || drivePreviewKind(driveFile) !== null)

  const driveThumb = useDrivePreviewThumb(driveFile, enabled && useDrive)
  const mailThumb = useMailBlobAttachmentThumb(att, enabled && !useDrive)

  return useDrive ? driveThumb : mailThumb
}

export { mailAttachmentCanThumb }
