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

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

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

  return (
    <div className="">
      <AutoSaveTextarea
        multiline={false}
        value={location.data.name}
        onSave={saveLocationName}
      />
      <AutoSaveTextarea
        value={location.data.description}
        onSave={saveLocationDescription}
      />
    </div>
  );
};
