"use client";

import * as React from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useSession } from "next-auth/react";
import { ChevronRight } from "lucide-react";

import { CollaborativeBlockEditor } from "@/components/editor";
import { api } from "@/lib/trpc";
import { Input } from "@/components/ui/input";

function contentToHtml(content: unknown): string {
  if (content == null) return "<p></p>";
  if (typeof content === "string") return content || "<p></p>";
  if (
    typeof content === "object" &&
    content !== null &&
    "html" in content &&
    typeof (content as { html: unknown }).html === "string"
  ) {
    return (content as { html: string }).html || "<p></p>";
  }
  return "<p></p>";
}

export default function DocEditorPage() {
  const params = useParams();
  const { data: session } = useSession();
  const utils = api.useUtils();

  const workspaceSlug =
    typeof params?.workspaceSlug === "string" ? params.workspaceSlug : undefined;
  const docId = typeof params?.docId === "string" ? params.docId : undefined;

  const docQuery = api.objects.getById.useQuery(
    { id: docId!, workspace: workspaceSlug! },
    { enabled: Boolean(docId) && Boolean(workspaceSlug) },
  );

  const doc = docQuery.data as
    | { id: string; title: string; content: unknown; type: string }
    | undefined;

  const [titleDraft, setTitleDraft] = React.useState("");

  React.useEffect(() => {
    if (doc?.title != null) setTitleDraft(doc.title);
  }, [doc?.title]);

  const saveContentTimeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(
    null,
  );

  React.useEffect(
    () => () => {
      if (saveContentTimeoutRef.current) {
        clearTimeout(saveContentTimeoutRef.current);
      }
    },
    [],
  );

  const updateMutation = api.objects.update.useMutation({
    onSuccess: async (_row, variables) => {
      if (!workspaceSlug) return;
      await utils.objects.getById.invalidate({ id: variables.id, workspace: workspaceSlug });
      void utils.objects.list.invalidate({ workspace: workspaceSlug });
    },
  });

  const scheduleContentSave = React.useCallback(
    (html: string) => {
      if (!docId || !workspaceSlug) return;
      if (saveContentTimeoutRef.current) {
        clearTimeout(saveContentTimeoutRef.current);
      }
      saveContentTimeoutRef.current = setTimeout(() => {
        saveContentTimeoutRef.current = null;
        updateMutation.mutate({ workspace: workspaceSlug, id: docId, content: html });
      }, 500);
    },
    [docId, workspaceSlug, updateMutation],
  );

  const handleTitleBlur = () => {
    if (!docId || !doc || !workspaceSlug) return;
    const next = titleDraft.trim();
    if (next.length === 0) {
      setTitleDraft(doc.title);
      return;
    }
    if (next === doc.title) return;
    updateMutation.mutate({ workspace: workspaceSlug, id: docId, title: next });
  };

  if (!docId || !workspaceSlug) {
    return (
      <div className="mx-auto max-w-4xl px-8 py-10 text-sm text-muted-foreground">
        Invalid document link.
      </div>
    );
  }

  if (docQuery.isPending) {
    return (
      <div className="mx-auto max-w-4xl px-8 py-10">
        <div className="animate-pulse space-y-4">
          <div className="h-4 w-48 rounded bg-muted" />
          <div className="h-10 w-full max-w-xl rounded-md bg-muted" />
          <div className="h-[320px] w-full rounded-xl bg-muted" />
        </div>
      </div>
    );
  }

  if (docQuery.isError || !doc) {
    return (
      <div className="mx-auto max-w-4xl px-8 py-10 text-sm text-muted-foreground">
        Could not load this document.
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-4xl px-8 py-10">
      <nav
        className="mb-6 flex flex-wrap items-center gap-1 text-sm text-muted-foreground"
        aria-label="Breadcrumb"
      >
        <Link
          href={`/${workspaceSlug}/docs`}
          className="hover:text-foreground"
        >
          Documents
        </Link>
        <ChevronRight className="size-4 shrink-0 opacity-60" />
        <span className="min-w-0 truncate text-foreground">{doc.title}</span>
      </nav>

      <Input
        value={titleDraft}
        onChange={(e) => setTitleDraft(e.target.value)}
        onBlur={handleTitleBlur}
        className="mb-6 border-0 border-b border-transparent bg-transparent px-0 text-3xl font-bold tracking-tight shadow-none focus-visible:border-border focus-visible:ring-0"
        placeholder="Untitled"
        aria-label="Document title"
      />

      <CollaborativeBlockEditor
        key={doc.id}
        documentId={doc.id}
        userName={session?.user?.name ?? undefined}
        content={contentToHtml(doc.content)}
        onChange={scheduleContentSave}
        placeholder="Start typing, or use '/' for commands..."
      />
    </div>
  );
}
