"use client"

import { useEffect, useMemo, useState } from "react"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { ArrowLeft } from "lucide-react"
import { UltidrawDocumentEditor } from "@/components/drive/ultidraw-document"
import {
  DocsEditorLoadingShell,
  useDocsEditorLoadingState,
} from "@/components/drive/richtext/docs-editor-loading-shell"
import { displayFileBaseName } from "@/lib/drive/display-file-name"
import {
  resolvePublicShareEditReturnTo,
  shouldShowPublicShareEditorBack,
} from "@/lib/drive/public-share-url"
import type { PublicShareRootType } from "@/lib/drive/public-share-url"
import { useDriveDocumentTitle } from "@/lib/drive/use-drive-document-title"
import { getGuestEditorIdentity } from "@/lib/drive/guest-editor-identity"
import type { UltidrawSessionResponse } from "@/lib/drive/ultidraw-types"
import { fetchPublicShareBlob } from "@/lib/api/public-share"

function fileNameFromPath(filePath: string, fallback?: string): string {
  const base = filePath.split("/").filter(Boolean).pop()
  return base || fallback || filePath
}

export function PublicUltidrawEditor({
  token,
  filePath,
  password,
  returnTo,
  mode = "edit",
  fileDisplayName,
  shareRoot,
}: {
  token: string
  filePath: string
  password?: string
  returnTo?: string | null
  mode?: "edit" | "view"
  fileDisplayName?: string
  shareRoot?: PublicShareRootType | null
}) {
  const guest = useMemo(() => getGuestEditorIdentity(token), [token])
  const [session, setSession] = useState<UltidrawSessionResponse | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [resolvedMode, setResolvedMode] = useState<"edit" | "view">(mode)

  const fileName = fileDisplayName || fileNameFromPath(filePath)
  const title = displayFileBaseName(fileName)
  useDriveDocumentTitle(title)

  const backHref = useMemo(
    () => resolvePublicShareEditReturnTo(token, returnTo, filePath),
    [token, returnTo, filePath]
  )
  const showBack = shouldShowPublicShareEditorBack(shareRoot, returnTo, filePath)

  useEffect(() => {
    let cancelled = false
    setSession(null)
    setError(null)
    void (async () => {
      try {
        const res = await fetch(
          `/api/v1/drive/public/shares/${encodeURIComponent(token)}/ultidraw/session`,
          {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              path: filePath,
              mode,
              password: password ?? "",
              guest_id: guest.guestId,
              guest_name: guest.guestName,
              display_name: fileName,
            }),
          }
        )
        if (!res.ok) throw new Error("Session indisponible")
        const data = (await res.json()) as UltidrawSessionResponse
        if (!cancelled) {
          setSession(data)
          setResolvedMode(data.mode === "view" ? "view" : mode)
        }
      } catch (e) {
        if (!cancelled) {
          setError(e instanceof Error ? e.message : "Impossible d'ouvrir le dessin")
        }
      }
    })()
    return () => {
      cancelled = true
    }
  }, [token, filePath, mode, password, guest.guestId, guest.guestName, fileName])

  const fetchSource = useMemo(
    () =>
      async (path: string) => {
        const blob = await fetchPublicShareBlob(
          token,
          { path, name: path.split("/").pop() ?? path },
          password
        )
        return await blob.text()
      },
    [token, password]
  )

  const { documentLoading, documentPhase, onDocumentLoadingChange } = useDocsEditorLoadingState(
    session?.roomId ?? filePath
  )

  if (error) {
    return (
      <div className="flex h-dvh flex-col items-center justify-center gap-4 p-8">
        <p className="text-sm text-muted-foreground">{error}</p>
        {showBack ? (
          <Button variant="outline" asChild>
            <Link href={backHref}>
              <ArrowLeft className="mr-2 h-4 w-4" />
              Retour
            </Link>
          </Button>
        ) : null}
      </div>
    )
  }

  return (
    <DocsEditorLoadingShell
      title={title}
      resolvingFile={false}
      awaitingSession={!session}
      documentLoading={Boolean(session) && documentLoading}
      documentPhase={documentPhase}
    >
      {session ? (
        <div className="flex h-full min-h-0 flex-col">
          {showBack ? (
            <div className="flex h-12 shrink-0 items-center border-b border-border px-3">
              <Button variant="ghost" size="sm" asChild>
                <Link href={backHref}>
                  <ArrowLeft className="mr-1 h-4 w-4" />
                  Retour
                </Link>
              </Button>
            </div>
          ) : null}
          <div className="min-h-0 flex-1">
            <UltidrawDocumentEditor
              session={session}
              mode={resolvedMode}
              userName={guest.guestName}
              userColor={guest.color}
              chrome={{
                title,
                showBack: false,
                showShare: false,
                showAccount: false,
              }}
              fetchDocument={fetchSource}
              deferSplash
              onLoadingChange={onDocumentLoadingChange}
            />
          </div>
        </div>
      ) : null}
    </DocsEditorLoadingShell>
  )
}
