"use client"

import { useParams, useSearchParams } from "next/navigation"
import { useEffect, useState } from "react"
import { PublicOfficeEditor } from "@/components/drive/public-office-editor"
import { PublicRichTextEditor } from "@/components/drive/public-richtext-editor"
import { PublicUltidrawEditor } from "@/components/drive/public-ultidraw-editor"
import { shouldOpenInRichTextEditor, shouldOpenInUltidrawEditor } from "@/lib/drive/drive-preview"
import { filePathFromPublicEditSegments, readPublicShareRootType } from "@/lib/drive/public-share-url"
import type { PublicShareRootType } from "@/lib/drive/public-share-url"

export default function PublicShareEditPage() {
  const params = useParams()
  const searchParams = useSearchParams()
  const token = String(params.token ?? "")
  const pathSegments = params.path as string[] | undefined
  const filePath = filePathFromPublicEditSegments(token, pathSegments)
  const returnTo = searchParams.get("returnTo")
  const mode = searchParams.get("mode") === "view" ? "view" : "edit"
  const fileDisplayName = searchParams.get("name") ?? undefined
  const editorParam = searchParams.get("editor")
  const shareRootParam = searchParams.get("shareRoot")
  const shareRootFromUrl: PublicShareRootType | null =
    shareRootParam === "file" || shareRootParam === "folder" ? shareRootParam : null
  const [shareRoot, setShareRoot] = useState<PublicShareRootType | null>(shareRootFromUrl)

  useEffect(() => {
    if (shareRootFromUrl) {
      setShareRoot(shareRootFromUrl)
      return
    }
    setShareRoot(readPublicShareRootType(token))
  }, [shareRootFromUrl, token])

  const [password] = useState<string | undefined>(() => {
    if (typeof window === "undefined") return undefined
    return sessionStorage.getItem(`public-share-pw:${token}`) ?? undefined
  })

  const fileName = fileDisplayName ?? filePath.split("/").pop() ?? ""

  const useUltidraw =
    editorParam === "ultidraw" || shouldOpenInUltidrawEditor({ name: fileName })

  const useRichText =
    editorParam === "richtext" || shouldOpenInRichTextEditor({ name: fileName })

  if (useUltidraw) {
    return (
      <PublicUltidrawEditor
        token={token}
        filePath={filePath}
        password={password}
        returnTo={returnTo}
        mode={mode}
        fileDisplayName={fileDisplayName}
        shareRoot={shareRoot}
      />
    )
  }

  if (useRichText) {
    return (
      <PublicRichTextEditor
        token={token}
        filePath={filePath}
        password={password}
        returnTo={returnTo}
        mode={mode}
        fileDisplayName={fileDisplayName}
        shareRoot={shareRoot}
      />
    )
  }

  return (
    <PublicOfficeEditor
      token={token}
      filePath={filePath}
      password={password}
      returnTo={returnTo}
      mode={mode}
      fileDisplayName={fileDisplayName}
      shareRoot={shareRoot}
    />
  )
}
