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

import {
  type ReviewDetail,
  type ReviewDetailFormQuestions,
  ReviewDirection,
} from 'src/pages/dashboard/performance/types';

import CalibrationAnswerPill from '../CalibrationDetail/components/CalibrationAnswerPill';

const buildQuestionMap = (
  questions: ReviewDetailFormQuestions[] | undefined,
) => {
  const map = new Map<string, ReviewDetailFormQuestions>();
  questions?.forEach(question => {
    if (question.id) map.set(question.id, question);
  });
  return map;
};

/**
 * Wires the "subordinate vs calibrated" comparison drawer into review views.
 *
 * Active only when the review is a SUBORDINATE_REVIEW with both `form` and
 * `calibrationForm` populated — that's when the calibrator overrides the
 * subordinate's answers and the user may want to inspect the original.
 *
 * Returns the state needed to render the eye-icon header action per question
 * and the props to spread into `CalibrationComparisonDrawer`.
 */
export const useReviewCalibrationComparison = (
  review: ReviewDetail | undefined,
) => {
  const isActive =
    review?.type === ReviewDirection.SUBORDINATE_REVIEW &&
    !!review?.calibrationForm &&
    !!review?.form;

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

  const subordinateQuestionsById = useMemo(
    () => (isActive ? buildQuestionMap(review?.form?.questions) : new Map()),
    [isActive, review?.form?.questions],
  );

  const calibratedQuestionsById = useMemo(
    () =>
      isActive
        ? buildQuestionMap(review?.calibrationForm?.questions)
        : new Map(),
    [isActive, review?.calibrationForm?.questions],
  );

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

  const getHeaderActions = useMemo(() => {
    if (!isActive) return undefined;
    return (question: ReviewDetailFormQuestions) => {
      if (!question.id || !subordinateQuestionsById.has(question.id)) {
        return null;
      }
      return (
        <CalibrationAnswerPill
          showPill={false}
          onEyeClick={() => setComparisonQuestionId(question.id ?? null)}
        />
      );
    };
  }, [isActive, subordinateQuestionsById]);

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

  return { isActive, getHeaderActions, drawerProps };
};
