import type { Editor } from "@tiptap/react"
import type { DocsExportSnapshot } from "@/lib/drive/docs-export-snapshot"
import {
  baseNameFromSource,
  downloadBlob,
  exportFileName,
} from "@/lib/drive/docs-export-download"
import type { TipTapJSON } from "@/lib/drive/richtext-import"

export type DocsDownloadFormat =
  | "docx"
  | "pdf"
  | "odt"
  | "txt"
  | "rtf"
  | "html"
  | "html-zip"
  | "epub"
  | "md"

export const DOCS_DOWNLOAD_FORMATS: { id: DocsDownloadFormat; label: string }[] = [
  { id: "docx", label: "Microsoft Word (.docx)" },
  { id: "pdf", label: "Document PDF (.pdf)" },
  { id: "odt", label: "Format OpenDocument (.odt)" },
  { id: "txt", label: "Texte brut (.txt)" },
  { id: "rtf", label: "Format texte enrichi (.rtf)" },
  { id: "html-zip", label: "Page Web (.html, zippé)" },
  { id: "epub", label: "Publication EPUB (.epub)" },
  { id: "md", label: "Markdown (.md)" },
]

export { downloadBlob, exportFileName } from "@/lib/drive/docs-export-download"

export async function exportDocsContent(
  format: DocsDownloadFormat,
  snapshot: DocsExportSnapshot | null,
  editor: Editor | null,
  sourceName: string
): Promise<"done" | "unsupported"> {
  if (!editor && !snapshot) return "unsupported"

  const base = baseNameFromSource(sourceName)

  switch (format) {
    case "docx": {
      if (!snapshot) return "unsupported"
      const { exportDocsToDocx } = await import("@/lib/drive/docs-docx-export")
      const blob = await exportDocsToDocx(snapshot)
      downloadBlob(blob, exportFileName(sourceName, "docx"))
      return "done"
    }
    case "pdf": {
      if (!snapshot) return "unsupported"
      const { exportDocsToPdf } = await import("@/lib/drive/docs-pdf-export")
      await exportDocsToPdf(snapshot)
      return "done"
    }
    case "txt": {
      if (!editor) return "unsupported"
      const text = editor.getText()
      downloadBlob(new Blob([text], { type: "text/plain;charset=utf-8" }), `${base}.txt`)
      return "done"
    }
    case "md": {
      if (!editor) return "unsupported"
      const text = editor.getText()
      downloadBlob(new Blob([text], { type: "text/markdown;charset=utf-8" }), `${base}.md`)
      return "done"
    }
    case "html": {
      if (!editor) return "unsupported"
      const html = `<!DOCTYPE html><html><head><meta charset="utf-8"><title>${base}</title></head><body>${editor.getHTML()}</body></html>`
      downloadBlob(new Blob([html], { type: "text/html;charset=utf-8" }), `${base}.html`)
      return "done"
    }
    default:
      return "unsupported"
  }
}

export type { TipTapJSON }
