import { cleanFilters } from '@/utils/clean-filters'
import { useMutation, useQuery } from '@tanstack/vue-query'
import {
  apiAddAdminExam,
  apiAddAdminExamQuestion,
  apiAddAdminQuestionOption,
  apiDeleteAdminExam,
  apiGetAdminExams,
  apiGetAdminExamAttempts,
  apiShowAdminExam,
  apiShowAdminExamAttempt,
  apiShowAdminExamParticipant,
  apiUpdateAdminExam,
} from '@/services/api/admin-exams'

export const adminExamsKeys = {
  all: ['admin', 'exams'],
  list: (filters, pagination) => ['admin', 'exams', 'list', filters, pagination],
  detail: (id) => ['admin', 'exams', 'detail', id],
  attempts: (examId, filters, pagination) => [
    'admin',
    'exams',
    'attempts',
    examId,
    filters,
    pagination,
  ],
  participantDetail: (examId, participantId) => [
    'admin',
    'exams',
    'participants',
    examId,
    'detail',
    participantId,
  ],
}

export const useAdminExamsListQuery = (filtersRef, paginationRef, options = {}) =>
  useQuery({
    queryKey: ['admin', 'exams', 'list', filtersRef, paginationRef],
    queryFn: () => apiGetAdminExams({ ...cleanFilters(filtersRef.value), ...paginationRef.value }),
    select: (response) => ({
      data: response?.data?.items ?? response?.data ?? [],
      meta: response?.data?.meta ?? response?.meta,
    }),
    ...options,
  })

export const useAdminExamQuery = (idRef, options = {}) =>
  useQuery({
    queryKey: ['admin', 'exams', 'detail', idRef],
    queryFn: () => apiShowAdminExam(idRef.value),
    select: (response) => response?.data ?? response,
    ...options,
  })

export const useAdminExamAttemptsQuery = (examIdRef, filtersRef, paginationRef, options = {}) =>
  useQuery({
    queryKey: ['admin', 'exams', 'attempts', examIdRef, filtersRef, paginationRef],
    queryFn: () =>
      apiGetAdminExamAttempts(examIdRef.value, {
        ...cleanFilters(filtersRef?.value || {}),
        ...paginationRef?.value,
      }),
    select: (response) => ({
      data: response?.data?.items ?? response?.data ?? [],
      meta: response?.data?.meta ?? response?.meta,
    }),
    ...options,
  })

export const useAdminExamParticipantQuery = (examIdRef, participantIdRef, options = {}) =>
  useQuery({
    queryKey: ['admin', 'exams', 'participants', examIdRef, 'detail', participantIdRef],
    queryFn: () => apiShowAdminExamParticipant(examIdRef.value, participantIdRef.value),
    select: (response) => response?.data ?? response,
    ...options,
  })

// GET /exam-attempts/:id — single attempt review. Adapts the backend payload
// into the shape ExamParticipantDetailsModal already renders (one accordion row
// with questions → answers, plus correct/selected ids for the dot states).
export const useAdminExamAttemptQuery = (idRef, options = {}) =>
  useQuery({
    queryKey: ['admin', 'exams', 'attempt', idRef],
    queryFn: () => apiShowAdminExamAttempt(idRef.value),
    select: (response) => {
      const a = response?.data ?? response
      if (!a) return null
      const exam = a.exam || {}
      const session = exam.session || {}
      const course = session.course || {}
      return {
        id: a.id,
        title: exam.title || 'آزمون',
        courseTitle: course.title || '—',
        sessionTitle: session.title || '—',
        date: a.submittedAt,
        score: a.score,
        scoreTone: a.isPassed ? 'good' : 'bad',
        questions: (a.questions || []).map((q) => {
          const correct = (q.options || []).find((o) => o.isCorrect)
          const selected = (q.options || []).find((o) => o.isSelected)
          return {
            id: q.id,
            title: q.questionText,
            answers: (q.options || []).map((o) => ({ id: o.id, title: o.optionText })),
            correctAnswerId: correct?.id ?? null,
            userAnswerId: q.selectedOptionId ?? selected?.id ?? null,
          }
        }),
      }
    },
    ...options,
  })

export const useAddAdminExamMutation = () =>
  useMutation({ mutationFn: (payload) => apiAddAdminExam(payload) })

export const useUpdateAdminExamMutation = () =>
  useMutation({ mutationFn: ({ id, payload }) => apiUpdateAdminExam(id, payload) })

export const useDeleteAdminExamMutation = () =>
  useMutation({ mutationFn: (id) => apiDeleteAdminExam(id) })

export const useAddAdminExamQuestionMutation = () =>
  useMutation({ mutationFn: ({ examId, payload }) => apiAddAdminExamQuestion(examId, payload) })

export const useAddAdminQuestionOptionMutation = () =>
  useMutation({
    mutationFn: ({ questionId, payload }) => apiAddAdminQuestionOption(questionId, payload),
  })
