/**
 * Start node (Zeitplan) — Accordion planner; gespeichert werden cron + schedule.
 */

import React, { useCallback, useMemo } from 'react';
import { flushSync } from 'react-dom';
import type { NodeConfigRendererProps } from '../shared/types';
import { SchedulePlanner } from '../../../SchedulePlanner';
import {
  buildCronFromSpec,
  scheduleSpecFromParams,
  scheduleSpecToPersistentJson,
  type ScheduleSpec,
} from '../runtime/scheduleCron';

export const ScheduleStartNodeConfig: React.FC<NodeConfigRendererProps> = ({ params, updateParam }) => {
  const spec = useMemo(
    () => scheduleSpecFromParams(params as Record<string, unknown>),
    [params.cron, params.schedule]
  );
  const push = useCallback(
    (next: ScheduleSpec) => {
      const sched = scheduleSpecToPersistentJson(next);
      const cron = buildCronFromSpec(next);
      flushSync(() => {
        updateParam('schedule', sched);
      });
      updateParam('cron', cron);
    },
    [updateParam]
  );
  return <SchedulePlanner value={spec} onChange={push} />;
};
