import { useEffect } from "react";
import { buildPresetSignature } from "../utils/presets.js";

export default function useTaskLifecycle({
  loadBase,
  selectedTaskId,
  loadSelectedTask,
  setAccessStatus,
  setInviteAccessStatus,
  setMembershipStatus,
  setTaskNotice,
  setActivePreset,
  checkAccess,
  checkInviteAccess,
  activePreset,
  taskForm,
  taskAccountRoles,
  presetSignatureRef
}) {
  useEffect(() => {
    loadBase();
  }, []);

  useEffect(() => {
    loadSelectedTask(selectedTaskId);
    setAccessStatus([]);
    setInviteAccessStatus([]);
    setMembershipStatus({});
    setTaskNotice(null);
    setActivePreset("");
    if (selectedTaskId != null) {
      checkAccess("auto", true);
      checkInviteAccess("auto", true);
    }
  }, [selectedTaskId]);

  useEffect(() => {
    if (!activePreset) return;
    const currentSignature = buildPresetSignature(taskForm, taskAccountRoles);
    if (currentSignature !== presetSignatureRef.current) {
      setActivePreset("");
    }
  }, [taskForm, taskAccountRoles, activePreset]);
}
