import { useCallback } from "react";
import { trpc } from "@/lib/trpc";
import { usePhaseAutoSave } from "@/hooks/usePhaseAutoSave";
import { TiptapEditor } from "./TiptapEditor";
import { Skeleton } from "@/components/Skeleton";

interface PhaseContentEditorProps {
  phaseId: string;
  initiativeId?: string;
}

export function PhaseContentEditor({ phaseId }: PhaseContentEditorProps) {
  const { save, isSaving } = usePhaseAutoSave();

  const phaseQuery = trpc.getPhase.useQuery({ id: phaseId });

  const handleUpdate = useCallback(
    (json: string) => {
      save(phaseId, { content: json });
    },
    [phaseId, save],
  );

  if (phaseQuery.isLoading) {
    return <Skeleton className="h-32 w-full" />;
  }

  if (phaseQuery.isError) {
    return null;
  }

  return (
    <div className="mb-3">
      {isSaving && (
        <div className="flex justify-end mb-1">
          <span className="text-xs text-muted-foreground">Saving...</span>
        </div>
      )}
      <TiptapEditor
        entityId={phaseId}
        content={phaseQuery.data?.content ?? null}
        onUpdate={handleUpdate}
        enablePageLinks={false}
      />
    </div>
  );
}
