"use client";

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

export default function WritePage() {
  const searchParams = useSearchParams();
  const appQuery = searchParams.get("app");

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

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

      try {
        // Fetch apps to find the one matching the query parameter string
        const apps = (await invoke("get_app")) as HomelabApp[];
        const matchedApp = apps.find(
          (app) =>
            app.id === appQuery ||
            app.name.toLowerCase() === appQuery.toLowerCase(),
        );

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

    checkQueryParam();
  }, [appQuery]);

  const onSave = (content: string, linkedAppIds: string[]) => {
    console.log("Document Rich Text: ", content);
    console.log("Document Bound App IDs: ", linkedAppIds);
  };

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

  return (
    <div className="flex flex-col p-2">
      <TextEditor
        content=""
        onSave={onSave}
        initialLinkedAppIds={initialAppIds}
      />
    </div>
  );
}
