import { useCallback, useMemo, useState } from 'react';

import { type CalibrationReviewDetail } from 'src/pages/dashboard/performance/types';

import { buildQuestionMap } from '../utils';

type UseCalibrationComparisonArgs = {
  detail: CalibrationReviewDetail;
};

/**
 * Manages the "compare calibrated vs original subordinate answer" drawer.
 *
 * - `openComparison(id)`: opens the drawer for that question id.
 * - `hasComparison(id)`: whether that question has a matching subordinate
 *   answer (i.e. the eye icon should be enabled).
 * - `drawerProps`: ready-to-spread props for `CalibrationComparisonDrawer`.
 */
export const useCalibrationComparison = ({
  detail,
}: UseCalibrationComparisonArgs) => {
  const { calibrationReview, subordinateReview } = detail;

  const [comparisonQuestionId, setComparisonQuestionId] = useState<
    string | null
  >(null);

  const subordinateQuestionsById = useMemo(
    () => buildQuestionMap(subordinateReview?.form?.questions),
    [subordinateReview],
  );
  const calibratedQuestionsById = useMemo(
    () => buildQuestionMap(calibrationReview.form?.questions),
    [calibrationReview],
  );

  const openComparison = useCallback(
    (id: string) => setComparisonQuestionId(id),
    [],
  );

  const closeComparison = useCallback(() => setComparisonQuestionId(null), []);

  const hasComparison = useCallback(
    (id: string | undefined): id is string =>
      !!id && subordinateQuestionsById.has(id),
    [subordinateQuestionsById],
  );

  const drawerProps = {
    open: comparisonQuestionId !== null,
    onClose: closeComparison,
    subordinateQuestion: comparisonQuestionId
      ? (subordinateQuestionsById.get(comparisonQuestionId) ?? null)
      : null,
    calibratedQuestion: comparisonQuestionId
      ? (calibratedQuestionsById.get(comparisonQuestionId) ?? null)
      : null,
  };

  return { openComparison, hasComparison, drawerProps };
};
