"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 { shouldOpenInRichTextEditor } 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 useRichText =
    editorParam === "richtext" ||
    shouldOpenInRichTextEditor({
      name: fileDisplayName ?? filePath.split("/").pop() ?? "",
    })

  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}
    />
  )
}
