import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { queryKeys } from "./keys";
import { adaptiveService } from "@/services";
import { taxonomyService } from "@/services";

export function useSubjects() {
  return useQuery({
    queryKey: queryKeys.taxonomy.subjects,
    queryFn: () => taxonomyService.listSubjects(),
  });
}

export function useTaxonomyTree(subjectId: number) {
  return useQuery({
    queryKey: queryKeys.taxonomy.tree(subjectId),
    queryFn: () => taxonomyService.getTaxonomyTree(subjectId),
    enabled: !!subjectId,
  });
}

export function useProficiency(params?: { subject_id?: number }) {
  return useQuery({
    queryKey: queryKeys.adaptive.proficiency(params),
    queryFn: () => adaptiveService.getProficiency(params ?? {}),
  });
}

export function useProficiencySummary() {
  return useQuery({
    queryKey: queryKeys.adaptive.summary,
    queryFn: () => adaptiveService.getProficiencySummary(),
  });
}

export function useLearningPlan(params?: { subject_id?: number }) {
  return useQuery({
    queryKey: queryKeys.adaptive.plan(params),
    queryFn: () => adaptiveService.getLearningPlan(params ?? {}),
    enabled: !!params?.subject_id,
  });
}

export function useTopicContent(topicId: number) {
  return useQuery({
    queryKey: queryKeys.adaptive.topicContent(topicId),
    queryFn: () => adaptiveService.getTopicContent(topicId),
    enabled: !!topicId,
  });
}

export function useStartDiagnostic() {
  return useMutation({
    mutationFn: (subjectId: number) => adaptiveService.startDiagnostic(subjectId),
  });
}

export function useAnswerDiagnostic() {
  return useMutation({
    mutationFn: adaptiveService.answerDiagnostic,
  });
}

export function useGenerateLearningPlan() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: { subject_id: number; target_completion?: string }) =>
      adaptiveService.generateLearningPlan(data),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["adaptive", "plan"] }),
  });
}

export function useSubmitMasteryQuiz() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ topicId, answers }: { topicId: number; answers: unknown[] }) =>
      adaptiveService.submitMasteryQuiz(topicId, answers),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["adaptive"] });
    },
  });
}
