/**
 * useQuiz Hooks
 * TanStack Query hooks for quiz functionality
 * OQI-002: Modulo Educativo
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { educationService } from '../../../services/education.service';
import type { Quiz, QuizAttempt, QuizResult, QuizAnswer } from '../../../types/education.types';

// ============================================================================
// Query Keys
// ============================================================================

export const quizKeys = {
  all: ['quizzes'] as const,
  detail: (quizId: string) => [...quizKeys.all, quizId] as const,
  byLesson: (lessonId: string) => [...quizKeys.all, 'lesson', lessonId] as const,
  byCourse: (courseId: string) => [...quizKeys.all, 'course', courseId] as const,
  attempts: (quizId: string) => [...quizKeys.all, quizId, 'attempts'] as const,
  result: (attemptId: string) => [...quizKeys.all, 'result', attemptId] as const,
  stats: (quizId: string) => [...quizKeys.all, quizId, 'stats'] as const,
  userStats: () => [...quizKeys.all, 'user-stats'] as const,
};

// ============================================================================
// Types
// ============================================================================

export interface QuizStats {
  totalAttempts: number;
  passRate: number;
  averageScore: number;
}

export interface UserQuizStats {
  totalAttempts: number;
  quizzesPassed: number;
  averageScore: number;
  bestScore: number;
}

export interface StartQuizResponse {
  attemptId: string;
  quiz: Quiz;
  startedAt: string;
  expiresAt?: string;
}

// ============================================================================
// Hooks
// ============================================================================

/**
 * Hook to fetch a quiz by ID
 */
export function useQuiz(quizId: string) {
  return useQuery<Quiz, Error>({
    queryKey: quizKeys.detail(quizId),
    queryFn: () => educationService.getQuizById(quizId),
    enabled: !!quizId,
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
}

/**
 * Hook to fetch quiz by lesson ID
 */
export function useQuizByLesson(lessonId: string) {
  return useQuery<Quiz | null, Error>({
    queryKey: quizKeys.byLesson(lessonId),
    queryFn: () => educationService.getQuizByLessonId(lessonId),
    enabled: !!lessonId,
    staleTime: 5 * 60 * 1000,
  });
}

/**
 * Hook to fetch all quizzes for a course
 */
export function useCourseQuizzes(courseId: string) {
  return useQuery<Quiz[], Error>({
    queryKey: quizKeys.byCourse(courseId),
    queryFn: () => educationService.getCourseQuizzes(courseId),
    enabled: !!courseId,
    staleTime: 5 * 60 * 1000,
  });
}

/**
 * Hook to fetch user's quiz attempts
 */
export function useQuizAttempts(quizId: string) {
  return useQuery<QuizAttempt[], Error>({
    queryKey: quizKeys.attempts(quizId),
    queryFn: () => educationService.getUserQuizAttempts(quizId),
    enabled: !!quizId,
    staleTime: 30 * 1000, // 30 seconds
  });
}

/**
 * Hook to fetch quiz result
 */
export function useQuizResult(attemptId: string) {
  return useQuery<QuizResult, Error>({
    queryKey: quizKeys.result(attemptId),
    queryFn: () => educationService.getQuizResults(attemptId),
    enabled: !!attemptId,
    staleTime: Infinity, // Results don't change
  });
}

/**
 * Hook to fetch quiz statistics
 */
export function useQuizStats(quizId: string) {
  return useQuery<QuizStats, Error>({
    queryKey: quizKeys.stats(quizId),
    queryFn: () => educationService.getQuizStatistics(quizId),
    enabled: !!quizId,
    staleTime: 5 * 60 * 1000,
  });
}

/**
 * Hook to fetch user's overall quiz stats
 */
export function useUserQuizStats() {
  return useQuery<UserQuizStats, Error>({
    queryKey: quizKeys.userStats(),
    queryFn: educationService.getUserQuizStats,
    staleTime: 60 * 1000, // 1 minute
  });
}

/**
 * Hook to start a quiz attempt
 */
export function useStartQuiz() {
  const queryClient = useQueryClient();

  return useMutation<
    StartQuizResponse,
    Error,
    { quizId: string; enrollmentId?: string }
  >({
    mutationFn: ({ quizId, enrollmentId }) =>
      educationService.startQuizAttempt(quizId, enrollmentId),
    onSuccess: (_, { quizId }) => {
      // Invalidate attempts list
      queryClient.invalidateQueries({ queryKey: quizKeys.attempts(quizId) });
    },
  });
}

/**
 * Hook to submit quiz answers
 */
export function useSubmitQuiz() {
  const queryClient = useQueryClient();

  return useMutation<
    QuizResult,
    Error,
    { attemptId: string; answers: { questionId: string; answer: string | string[] }[] }
  >({
    mutationFn: ({ attemptId, answers }) =>
      educationService.submitQuizAttempt(attemptId, answers),
    onSuccess: (result) => {
      // Cache the result
      queryClient.setQueryData(quizKeys.result(result.attempt.id), result);

      // Invalidate related queries
      queryClient.invalidateQueries({ queryKey: quizKeys.attempts(result.attempt.quizId) });
      queryClient.invalidateQueries({ queryKey: quizKeys.stats(result.attempt.quizId) });
      queryClient.invalidateQueries({ queryKey: quizKeys.userStats() });
    },
  });
}

export default useQuiz;
