import { useEffect, useRef, useState } from "react";
import { TaskValidationResult } from "./TasksEditor";

export function useValidation(
  runValidation: () => TaskValidationResult,
  onValidate: (result: TaskValidationResult) => void,
  deps: unknown[],
) {
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
  const prevErrorsRef = useRef<Record<string, string>>({});
  const prevInitialValidationRef = useRef<TaskValidationResult | null>(null);

  useEffect(() => {
    const result = runValidation();
    const prev = prevInitialValidationRef.current;

    const changed =
      !prev ||
      prev.isValid !== result.isValid ||
      Object.keys(prev.errors).length !== Object.keys(result.errors).length ||
      Object.entries(result.errors).some(([k, v]) => prev.errors[k] !== v);

    if (changed) {
      setFieldErrors(result.errors);
      prevErrorsRef.current = result.errors;
      onValidate(result);
      prevInitialValidationRef.current = result;
    }
  }, deps);

  return { fieldErrors };
}
