"use client"

import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { DocsLoadingSplash } from "@/components/drive/richtext/docs-loading-splash"
import { apiClient } from "@/lib/api/client"
import type { DriveFileInfo } from "@/lib/api/types"
import { stashDriveEditorReturnTo } from "@/lib/drive/drive-editor-return"
import { buildDriveDocsEditHref } from "@/lib/drive/drive-url"

/** Redirect path-based /drive/edit URLs to stable id-based /drive/docs URLs. */
export function RichTextEditorLegacyRedirect({
  filePath,
  returnTo,
}: {
  filePath: string
  returnTo?: string | null
}) {
  const router = useRouter()
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (returnTo) stashDriveEditorReturnTo(returnTo)
    else stashDriveEditorReturnTo()
    let cancelled = false
    void (async () => {
      try {
        const info = await apiClient.get<DriveFileInfo>(
          `/drive/files/info${filePath.startsWith("/") ? filePath : `/${filePath}`}`
        )
        if (cancelled) return
        if (!info.file_id) {
          setError("Identifiant du document introuvable")
          return
        }
        router.replace(buildDriveDocsEditHref(info.file_id))
      } catch (e) {
        if (!cancelled) {
          setError(e instanceof Error ? e.message : "Impossible d'ouvrir le document")
        }
      }
    })()
    return () => {
      cancelled = true
    }
  }, [filePath, returnTo, router])

  if (error) {
    return (
      <div className="flex h-dvh items-center justify-center p-8 text-sm text-muted-foreground">
        {error}
      </div>
    )
  }

  return <DocsLoadingSplash phase="opening" />
}
