import { useMemo, useState } from 'react';
import { useContentCatalogPayload } from '@/business/content-catalog/hooks';
import {
  useCurrentPersonalityResult,
  usePersonalityDistribution,
  useSaveCurrentPersonalityResult,
} from '@/business/personality/queryHooks';
import {
  getEmotionalIntelligenceLevel,
  getPersonalityGroup,
  groupPersonalityDistribution,
  totalPersonalityDistribution,
} from '@/business/personality/selectors';
import { CONTENT_CATALOG_TYPES } from '@/shared/constants/contentCatalog';
import type { UserRole } from '@/shared/types/app';
import type {
  EmotionalIntelligenceQuestion,
  EmotionalIntelligenceTab,
  EmotionalIntelligenceTopic,
  EmotionalIntelligenceWeeklyFocus,
  PersonalityWorkplaceContent,
  TeamWellnessMetric,
} from '@/shared/types/emotionalIntelligence';
import type { PersonalityDistributionDto } from '@/shared/types/personality';
import type { PersonalityType } from '@/shared/constants/personalityCatalog';
import { getOptionalErrorMessage } from '@/shared/errors/errorMessages';
import { getFirstQueryError, isAnyLoading } from '@/shared/business/queryState';

const EMPTY_PERSONALITY_DISTRIBUTION: readonly PersonalityDistributionDto[] = [];

export function useEmotionalIntelligencePage(userRole: UserRole) {
  const assessmentQuestionsQuery = useContentCatalogPayload<readonly EmotionalIntelligenceQuestion[]>(
    CONTENT_CATALOG_TYPES.emotionalIntelligenceAssessmentQuestions,
    [],
  );
  const weeklyTopicsQuery = useContentCatalogPayload<readonly EmotionalIntelligenceTopic[]>(
    CONTENT_CATALOG_TYPES.emotionalIntelligenceWeeklyTopics,
    [],
  );
  const growthTipsQuery = useContentCatalogPayload<readonly string[]>(
    CONTENT_CATALOG_TYPES.emotionalIntelligenceGrowthTips,
    [],
  );
  const teamWellnessMetricsQuery = useContentCatalogPayload<readonly TeamWellnessMetric[]>(
    CONTENT_CATALOG_TYPES.emotionalIntelligenceTeamWellnessMetrics,
    [],
  );
  const weeklyFocusQuery = useContentCatalogPayload<EmotionalIntelligenceWeeklyFocus | null>(
    CONTENT_CATALOG_TYPES.emotionalIntelligenceWeeklyFocus,
    null,
  );
  const personalityWorkplaceContentQuery = useContentCatalogPayload<PersonalityWorkplaceContent | null>(
    CONTENT_CATALOG_TYPES.personalityWorkplaceContent,
    null,
  );
  const personalityTypesQuery = useContentCatalogPayload<readonly PersonalityType[]>(
    CONTENT_CATALOG_TYPES.personalityTypes,
    [],
  );
  const [activeTab, setActiveTab] = useState<EmotionalIntelligenceTab>('assessment');
  const [assessmentStarted, setAssessmentStarted] = useState(false);
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [answers, setAnswers] = useState<readonly number[]>([]);
  const [assessmentComplete, setAssessmentComplete] = useState(false);

  const currentPersonalityQuery = useCurrentPersonalityResult();
  const savePersonalityMutation = useSaveCurrentPersonalityResult();
  const canViewPersonalityDistribution = userRole === 'director' || userRole === 'superintendent';
  const personalityDistributionQuery = usePersonalityDistribution(undefined, canViewPersonalityDistribution);

  const savedPersonality = currentPersonalityQuery.data;
  const personalityResult = savedPersonality?.personalityType ?? null;
  const savedAnswers = savedPersonality?.quizAnswers ?? null;
  const savedDate = savedPersonality?.updatedAt ?? null;
  const distribution = personalityDistributionQuery.data ?? EMPTY_PERSONALITY_DISTRIBUTION;
  const distributionTotal = totalPersonalityDistribution(distribution);
  const groupDistribution = useMemo(
    () => groupPersonalityDistribution(distribution, getPersonalityGroup),
    [distribution],
  );
  const totalScore = answers.reduce((sum, score) => sum + score, 0);
  const assessmentQuestions = assessmentQuestionsQuery.payload;
  const maxScore = assessmentQuestions.length * 4;
  const percentage = maxScore > 0 ? Math.round((totalScore / maxScore) * 100) : 0;
  const assessmentLevel = getEmotionalIntelligenceLevel(percentage);
  const personalityError = currentPersonalityQuery.error ?? savePersonalityMutation.error;
  const distributionError = personalityDistributionQuery.error;
  const contentQueries = [
    assessmentQuestionsQuery,
    weeklyTopicsQuery,
    growthTipsQuery,
    teamWellnessMetricsQuery,
    weeklyFocusQuery,
    personalityWorkplaceContentQuery,
    personalityTypesQuery,
  ];

  const handleAnswer = (scoreIndex: number) => {
    const question = assessmentQuestions[currentQuestionIndex];
    if (!question) {
      return;
    }
    const nextAnswers = [...answers, question.scores[scoreIndex]];
    setAnswers(nextAnswers);

    if (currentQuestionIndex < assessmentQuestions.length - 1) {
      setCurrentQuestionIndex((index) => index + 1);
      return;
    }

    setAssessmentComplete(true);
  };

  const resetAssessment = () => {
    setAssessmentStarted(false);
    setCurrentQuestionIndex(0);
    setAnswers([]);
    setAssessmentComplete(false);
  };

  const handlePersonalityResult = async (code: string, quizAnswers: Record<number, string>) => {
    await savePersonalityMutation.mutateAsync({
      personalityType: code,
      quizAnswers,
    });
  };

  return {
    state: {
      activeTab,
      assessmentStarted,
      currentQuestionIndex,
      answers,
      assessmentComplete,
      totalScore,
      maxScore,
      percentage,
      assessmentLevel,
      currentPersonalityQuery,
      personalityDistributionQuery,
      canViewPersonalityDistribution,
      savedPersonality,
      personalityResult,
      savedAnswers,
      savedDate,
      isSaving: savePersonalityMutation.isPending,
      isLoadingSaved: currentPersonalityQuery.isLoading,
      distribution,
      distributionLoading: personalityDistributionQuery.isLoading || personalityDistributionQuery.isFetching,
      distributionTotal,
      groupDistribution,
      errorMessage: getOptionalErrorMessage(personalityError),
      distributionErrorMessage: getOptionalErrorMessage(distributionError),
      isDirector: userRole === 'director',
      assessmentQuestions,
      weeklyTopics: weeklyTopicsQuery.payload,
      growthTips: growthTipsQuery.payload,
      teamWellnessMetrics: teamWellnessMetricsQuery.payload,
      weeklyFocus: weeklyFocusQuery.payload,
      personalityWorkplaceContent: personalityWorkplaceContentQuery.payload,
      personalityTypes: personalityTypesQuery.payload,
      contentLoading: isAnyLoading(...contentQueries),
      contentError: getFirstQueryError(...contentQueries),
    },
    actions: {
      setActiveTab,
      setAssessmentStarted,
      handleAnswer,
      resetAssessment,
      handlePersonalityResult,
      refreshDistribution: () => personalityDistributionQuery.refetch(),
    },
  };
}
