import { useMemo } from 'react';
import { useFormContext, useWatch } from 'react-hook-form';

import isNil from 'lodash-es/isNil';

import {
  COMMENT,
  ReviewCommentableStatus,
  type ReviewDetailFormQuestions,
} from 'src/pages/dashboard/performance/types';

const isEmptyValue = (value: unknown) => {
  if (isNil(value)) return true;
  if (typeof value === 'string' && value.trim() === '') return true;
  if (Array.isArray(value) && value.length === 0) return true;
  return false;
};

export function useCurrentStepValidation(
  currentStepQuestions: ReviewDetailFormQuestions[],
) {
  const { control } = useFormContext();

  const { requiredAnswerIds, requiredCommentIds } = useMemo(() => {
    const answerIds: string[] = [];
    const commentIds: string[] = [];

    for (const q of currentStepQuestions) {
      const id = q.id ?? '';
      if (q.required) answerIds.push(id);
      if (q.commentableStatus === ReviewCommentableStatus.REQUIRED) {
        commentIds.push(`${id}${COMMENT}`);
      }
    }

    return { requiredAnswerIds: answerIds, requiredCommentIds: commentIds };
  }, [currentStepQuestions]);

  const watchedAnswers = useWatch({ name: requiredAnswerIds, control });
  const watchedComments = useWatch({ name: requiredCommentIds, control });

  return useMemo(() => {
    return currentStepQuestions.every(q => {
      const id = q.id ?? '';

      const answer = watchedAnswers[requiredAnswerIds.indexOf(id)];
      const answerMissing = q.required && isEmptyValue(answer);
      if (answerMissing) return false;

      const commentRequired =
        q.commentableStatus === ReviewCommentableStatus.REQUIRED;
      if (!commentRequired) return true;

      // Only enforce the comment when an answer is present — there's nothing
      // to comment on otherwise (and non-required questions can stay empty).
      if (isEmptyValue(answer)) return true;

      const comment =
        watchedComments[requiredCommentIds.indexOf(`${id}${COMMENT}`)];
      return !isEmptyValue(comment);
    });
  }, [
    currentStepQuestions,
    requiredAnswerIds,
    requiredCommentIds,
    watchedAnswers,
    watchedComments,
  ]);
}
