import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import * as db from '@/lib/db';
import { FlashcardSet, Flashcard } from '@/lib/mockData';

export const useFlashcardSets = () => {
    return useQuery({
        queryKey: ['flashcardSets'],
        queryFn: db.getFlashcardSets
    });
}

export const useFlashcardSet = (id: string) => {
    return useQuery({
        queryKey: ['flashcardSet', id],
        queryFn: () => db.getFlashcardSetById(id),
        enabled: !!id
    });
}

export const useCreateFlashcardSet = () => {
    const queryClient = useQueryClient();
    return useMutation({
        mutationFn: (data: { title: string, topic: string, color: string }) =>
            db.createFlashcardSet(data.title, data.topic, data.color),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['flashcardSets'] });
        }
    });
}

export const useDeleteFlashcardSet = () => {
    const queryClient = useQueryClient();
    return useMutation({
        mutationFn: db.deleteFlashcardSet,
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['flashcardSets'] });
        }
    });
}

export const useCreateFlashcard = () => {
    const queryClient = useQueryClient();
    return useMutation({
        mutationFn: (data: { setId: string, front: string, back: string }) =>
            db.createFlashcard(data.setId, data.front, data.back),
        onSuccess: (_, variables) => {
            queryClient.invalidateQueries({ queryKey: ['flashcardSet', variables.setId] });
            queryClient.invalidateQueries({ queryKey: ['flashcardSets'] }); // Update counts
        }
    });
}

export const useUpdateFlashcard = () => {
    const queryClient = useQueryClient();
    return useMutation({
        mutationFn: (data: { id: string, front: string, back: string, setId: string }) =>
            db.updateFlashcard(data.id, data.front, data.back),
        onSuccess: (_, variables) => {
            queryClient.invalidateQueries({ queryKey: ['flashcardSet', variables.setId] });
            queryClient.invalidateQueries({ queryKey: ['flashcardSets'] });
        }
    });
}

export const useDeleteFlashcard = () => {
    const queryClient = useQueryClient();
    return useMutation({
        mutationFn: (data: { id: string, setId: string }) => db.deleteFlashcard(data.id),
        onSuccess: (_, variables) => {
            queryClient.invalidateQueries({ queryKey: ['flashcardSet', variables.setId] });
            queryClient.invalidateQueries({ queryKey: ['flashcardSets'] });
        }
    });
}
