"use client";

import { useEffect, useState, Suspense } from "react";
import { useSearchParams } from "next/navigation";
import { invoke } from "@tauri-apps/api/core";
import TextEditor from "@/components/text-editor";
import { HomelabApp, Blog } from "@/types";

function WritePageContent() {
  const searchParams = useSearchParams();
  const appQuery = searchParams.get("app");

  const [initialAppIds, setInitialAppIds] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);

  // Track the document ID to allow updating instead of duplicating
  const [documentId, setDocumentId] = useState<string | null>(null);

  useEffect(() => {
    const checkQueryParam = async () => {
      if (!appQuery) {
        setLoading(false);
        return;
      }

      try {
        const apps = (await invoke("get_app")) as HomelabApp[];

        const matchedApp = apps.find(
          (app) =>
            app.id === appQuery ||
            app.name.toLowerCase().trim() === appQuery.toLowerCase().trim(),
        );

        if (matchedApp) {
          setInitialAppIds([matchedApp.id]);
        }
      } catch (error) {
        console.error(
          "Failed to fetch apps for query parameter auto-link:",
          error,
        );
      } finally {
        setLoading(false);
      }
    };

    checkQueryParam();
  }, [appQuery]);

  // Updated onSave signature matching what TextEditor emits
  const onSave = async (
    content: string,
    linkedAppIds: string[],
    title: string,
  ) => {
    try {
      const savedBlog = await invoke<Blog>("save_blog", {
        id: documentId,
        title: title || "Untitled Document",
        content: content,
        linkedAppIds: linkedAppIds,
      });

      // Update state with the backend-generated/returned ID
      if (savedBlog && savedBlog.id) {
        setDocumentId(savedBlog.id);
      }
    } catch (error) {
      console.error("Failed to save document:", error);
    }
  };

  if (loading) {
    return (
      <div className="p-4 text-sm text-zinc-400">Loading workspace...</div>
    );
  }

  return (
    <TextEditor
      content=""
      onSave={onSave}
      initialLinkedAppIds={initialAppIds}
    />
  );
}

export default function WritePage() {
  return (
    <div className="flex flex-col p-2">
      <Suspense
        fallback={
          <div className="p-4 text-sm text-zinc-400">
            Loading router state...
          </div>
        }
      >
        <WritePageContent />
      </Suspense>
    </div>
  );
}
