"use client"

import { useParams, useSearchParams } from "next/navigation"
import { OfficeEditor } from "@/components/drive/office-editor"
import { RichTextEditorLegacyRedirect } from "@/components/drive/richtext-legacy-redirect"
import { shouldOpenInRichTextEditor } from "@/lib/drive/drive-preview"
import { isDriveFileIdSegment } from "@/lib/drive/drive-url"

export default function DriveEditPage() {
  const params = useParams()
  const searchParams = useSearchParams()
  const rawId = params.fileId as string
  const returnTo = searchParams.get("returnTo")
  const editorParam = searchParams.get("editor")

  if (isDriveFileIdSegment(rawId)) {
    return (
      <div className="flex h-dvh items-center justify-center p-8 text-sm text-muted-foreground">
        Ouvrez ce document via /drive/docs/{rawId}/edit
      </div>
    )
  }

  const filePath = decodeURIComponent(rawId)
  const fileName = filePath.split("/").pop() ?? filePath
  const useRichText =
    editorParam === "richtext" || shouldOpenInRichTextEditor({ name: fileName })

  if (useRichText) {
    return <RichTextEditorLegacyRedirect filePath={filePath} returnTo={returnTo} />
  }

  return <OfficeEditor filePath={filePath} returnTo={returnTo} />
}
