"use client";

import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { ArrowUpRight, FileText, Loader2 } from "lucide-react";
import { NodeViewWrapper } from "@tiptap/react";
import type { NodeViewProps } from "@tiptap/react";
import { createClient, getBrowserUserId } from "@/lib/supabase/client";
import type { NoteLinkOptions } from "./note-link-node";

interface NoteLinkBlockViewProps extends NodeViewProps {
  options: NoteLinkOptions;
}

const EMPTY_NOTE_CONTENT = { type: "doc", content: [{ type: "paragraph" }] };

export function NoteLinkBlockView({ node, updateAttributes, options }: NoteLinkBlockViewProps) {
  const router = useRouter();
  const noteId = node.attrs.noteId as string | null;
  const title = node.attrs.title as string;
  const creatingRef = useRef(false);
  const [failed, setFailed] = useState(false);

  useEffect(() => {
    if (noteId || creatingRef.current) return;
    creatingRef.current = true;

    async function createSubNote() {
      const supabase = createClient();
      const userId = await getBrowserUserId();
      if (!userId) {
        setFailed(true);
        return;
      }
      const { data, error } = await supabase
        .from("notes")
        .insert({
          user_id: userId,
          team_id: options.parentTeamId,
          folder_id: options.parentFolderId,
          project_id: options.parentProjectId,
          parent_note_id: options.parentNoteId,
          title: "Untitled",
          content: EMPTY_NOTE_CONTENT,
        })
        .select("id, title")
        .single();

      if (error || !data) {
        console.error("Could not create sub-note", error);
        setFailed(true);
        return;
      }
      updateAttributes({ noteId: data.id, title: data.title });
    }

    void createSubNote();
  }, [
    noteId,
    options.parentFolderId,
    options.parentNoteId,
    options.parentProjectId,
    options.parentTeamId,
    updateAttributes,
  ]);

  function handleOpen() {
    if (!noteId) return;
    router.push(`/notes/${noteId}`);
  }

  return (
    <NodeViewWrapper className="my-2" contentEditable={false}>
      <button
        type="button"
        onClick={handleOpen}
        disabled={!noteId}
        className="group flex w-full items-center gap-2.5 rounded-xl border border-border bg-card/60 px-3.5 py-2.5 text-left transition-colors hover:bg-accent/40 disabled:cursor-wait"
      >
        <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-accent text-accent-foreground">
          {noteId ? <FileText className="h-3.5 w-3.5" /> : <Loader2 className="h-3.5 w-3.5 animate-spin" />}
        </span>
        <span className="min-w-0 flex-1 truncate text-[13px] font-medium">
          {failed ? "Could not create note" : title}
        </span>
        {noteId && (
          <ArrowUpRight className="h-3.5 w-3.5 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />
        )}
      </button>
    </NodeViewWrapper>
  );
}
