import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { queryKeys } from "./keys";
import { lmsService } from "@/services";
import type { PaginationParams, CourseCreateRequest, LmsStudentCreateRequest, LmsTeacherCreateRequest } from "@/types";

export function useCourses(params?: PaginationParams & { status?: string }) {
  return useQuery({
    queryKey: queryKeys.lms.courses(params),
    queryFn: () => lmsService.listCourses(params),
  });
}

export function useCourse(id: number) {
  return useQuery({
    queryKey: queryKeys.lms.course(id),
    queryFn: () => lmsService.getCourse(id),
    enabled: !!id,
  });
}

export function useCreateCourse() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: CourseCreateRequest) => lmsService.createCourse(data),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["lms", "courses"] }),
  });
}

export function useStudents(params?: PaginationParams & { search?: string; batch_id?: number }) {
  return useQuery({
    queryKey: queryKeys.lms.students(params),
    queryFn: () => lmsService.listStudents(params),
  });
}

export function useCreateStudent() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: LmsStudentCreateRequest) => lmsService.createStudent(data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["lms", "students"] });
    },
  });
}

export function useTeachers(params?: PaginationParams & { search?: string }) {
  return useQuery({
    queryKey: queryKeys.lms.teachers(params),
    queryFn: () => lmsService.listTeachers(params),
  });
}

export function useCreateTeacher() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: LmsTeacherCreateRequest) => lmsService.createTeacher(data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["lms", "teachers"] });
    },
  });
}

export function useBatches(params?: PaginationParams) {
  return useQuery({
    queryKey: queryKeys.lms.batches(params),
    queryFn: () => lmsService.listBatches(params),
  });
}

export function useBatch(id: number) {
  return useQuery({
    queryKey: queryKeys.lms.batch(id),
    queryFn: () => lmsService.getBatch(id),
    enabled: !!id,
  });
}

export function useTimetable(params?: Record<string, unknown>) {
  return useQuery({
    queryKey: queryKeys.lms.timetable(params),
    queryFn: () => lmsService.getTimetable(params as Record<string, string | number | boolean | undefined>),
  });
}

export function useAttendance(params?: Record<string, unknown>) {
  return useQuery({
    queryKey: queryKeys.lms.attendance(params),
    queryFn: () => lmsService.getAttendance(params as Record<string, string | number | boolean | undefined>),
  });
}

export function useGrades(params?: Record<string, unknown>) {
  return useQuery({
    queryKey: queryKeys.lms.grades(params),
    queryFn: () => lmsService.getGrades(params as Record<string, string | number | boolean | undefined>),
  });
}
