import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
import { useDocumentCache } from "@/context/document/hooks";
import { pb } from "@/lib/pocketbase";
import type { Npc } from "@/lib/types";

/**
 * Renders an editable npc form
 */
export const NpcEditForm = ({ npc }: { npc: Npc }) => {
  const { dispatch } = useDocumentCache();
  async function saveNpcName(name: string) {
    const updated: Npc = await pb.collection("documents").update(npc.id, {
      data: {
        ...npc.data,
        name,
      },
    });
    dispatch({ type: "setDocument", doc: updated });
  }

  async function saveNpcDescription(description: string) {
    const updated: Npc = await pb.collection("documents").update(npc.id, {
      data: {
        ...npc.data,
        description,
      },
    });
    dispatch({ type: "setDocument", doc: updated });
  }

  return (
    <div className="">
      <AutoSaveTextarea
        multiline={false}
        value={npc.data.name}
        onSave={saveNpcName}
      />
      <AutoSaveTextarea
        value={npc.data.description}
        onSave={saveNpcDescription}
      />
    </div>
  );
};
