import { useMutation, useQueryClient } from '@tanstack/react-query';
import {
    markMessageAsSeen,
    moveMessageToArchive,
    moveMessageToFavorite,
    moveMessageToTrash,
    deleteMessagePermanently,
    sendEmail,
    updateDraft,
    deleteDraft,
    sendDraft,
    bulkAction,
    unfavoriteMessage,
    unarchiveMessage,
    restoreMessage,
} from '../services/EmailActionsService';
import { BulkActionType } from '../pages/received/types/Types';
import { toast } from '../components/Toast';

export const useEmailActions = (customRefetch?: () => void) => {
    const queryClient = useQueryClient();

    // تمام query key های موجود در سیستم
    const invalidateAllQueries = () => {
        // صفحه‌های اصلی
        queryClient.invalidateQueries({ queryKey: ['inbox'] });
        queryClient.invalidateQueries({ queryKey: ['drafts'] });
        queryClient.invalidateQueries({ queryKey: ['archive-messages'] });
        queryClient.invalidateQueries({ queryKey: ['favorite-messages'] });
        queryClient.invalidateQueries({ queryKey: ['spam-messages'] });
        queryClient.invalidateQueries({ queryKey: ['trash-messages'] });
        queryClient.invalidateQueries({ queryKey: ['search-messages'] });

        // پیام‌های تکی
        queryClient.invalidateQueries({ queryKey: ['message'] });
        queryClient.invalidateQueries({ queryKey: ['draft'] });

        // صفحه‌هایی که از React Query استفاده نمی‌کنند (مثل sent)
        if (customRefetch) {
            customRefetch();
        }
    };

    const bulkActionMutation = useMutation({
        mutationFn: bulkAction,
        onSuccess: (data) => {
            toast(data?.data?.message || 'عملیات گروهی با موفقیت انجام شد', 'success');
            invalidateAllQueries();
        },
    });

    const markAsSeenMutation = useMutation({
        mutationFn: ({ messageId, mailbox }: { messageId: number; mailbox: string }) => markMessageAsSeen(messageId, mailbox),
        onSuccess: (data) => {
            toast(data?.data?.message || 'پیام به عنوان خوانده شده علامت‌گذاری شد', 'success');
            invalidateAllQueries();
        },
    });

    const archiveMutation = useMutation({
        mutationFn: ({ messageId, mailbox }: { messageId: number; mailbox: string }) => moveMessageToArchive(messageId, mailbox),
        onSuccess: (data) => {
            toast(data?.data?.message || 'پیام به آرشیو منتقل شد', 'success');
            invalidateAllQueries();
        },
    });

    const favoriteMutation = useMutation({
        mutationFn: ({ messageId, mailbox }: { messageId: number; mailbox: string }) => moveMessageToFavorite(messageId, mailbox),
        onSuccess: (data) => {
            toast(data?.data?.message || 'پیام به علاقه‌مندی‌ها اضافه شد', 'success');
            invalidateAllQueries();
        },
    });

    const moveToTrashMutation = useMutation({
        mutationFn: ({ messageId, mailbox }: { messageId: number; mailbox: string }) => moveMessageToTrash(messageId, mailbox),
        onSuccess: (data) => {
            toast(data?.data?.message || 'پیام به سطل زباله منتقل شد', 'success');
            invalidateAllQueries();
        },
    });

    const deletePermanentlyMutation = useMutation({
        mutationFn: ({ messageId, mailbox }: { messageId: number; mailbox: string }) => deleteMessagePermanently(messageId, mailbox),
        onSuccess: (data) => {
            toast(data?.data?.message || 'پیام به طور کامل حذف شد', 'success');
            invalidateAllQueries();
        },
    });

    const sendEmailMutation = useMutation({
        mutationFn: ({ messageId }: { messageId: number }) => sendEmail(messageId),
        onSuccess: (data) => {
            toast(data?.data?.message || 'ایمیل با موفقیت ارسال شد', 'success');
            invalidateAllQueries();
        },
    });

    const updateDraftMutation = useMutation({
        mutationFn: ({ messageId, draftData }: { messageId: number; draftData: unknown }) =>
            updateDraft(messageId, draftData),
        onSuccess: (data) => {
            toast(data?.data?.message || 'پیش‌نویس به‌روزرسانی شد', 'success');
            invalidateAllQueries();
        },
    });

    const deleteDraftMutation = useMutation({
        mutationFn: ({ messageId, mailbox }: { messageId: number; mailbox: string }) => deleteDraft(messageId, mailbox),
        onSuccess: (data) => {
            toast(data?.data?.message || 'پیش‌نویس حذف شد', 'success');
            invalidateAllQueries();
        },
    });

    const sendDraftMutation = useMutation({
        mutationFn: ({ messageId }: { messageId: number }) => sendDraft(messageId),
        onSuccess: (data) => {
            toast(data?.data?.message || 'پیش‌نویس ارسال شد', 'success');
            invalidateAllQueries();
        },
    });

    const unfavoriteMutation = useMutation({
        mutationFn: ({ messageId, mailbox }: { messageId: number; mailbox: string }) => unfavoriteMessage(messageId, mailbox),
        onSuccess: (data) => {
            toast(data?.data?.message || 'پیام از علاقه‌مندی‌ها حذف شد', 'success');
            invalidateAllQueries();
        },
    });

    const unarchiveMutation = useMutation({
        mutationFn: ({ messageId, mailbox }: { messageId: number; mailbox: string }) => unarchiveMessage(messageId, mailbox),
        onSuccess: (data) => {
            toast(data?.data?.message || 'پیام از آرشیو خارج شد', 'success');
            invalidateAllQueries();
        },
    });

    const restoreMutation = useMutation({
        mutationFn: ({ messageId, mailbox }: { messageId: number; mailbox: string }) => restoreMessage(messageId, mailbox),
        onSuccess: (data) => {
            toast(data?.data?.message || 'پیام بازگردانی شد', 'success');
            invalidateAllQueries();
        },
    });

    const isLoading =
        bulkActionMutation.isPending ||
        markAsSeenMutation.isPending ||
        archiveMutation.isPending ||
        favoriteMutation.isPending ||
        moveToTrashMutation.isPending ||
        deletePermanentlyMutation.isPending ||
        sendEmailMutation.isPending ||
        updateDraftMutation.isPending ||
        deleteDraftMutation.isPending ||
        sendDraftMutation.isPending ||
        unfavoriteMutation.isPending ||
        unarchiveMutation.isPending ||
        restoreMutation.isPending;

    return {
        // Bulk actions
        bulkAction: bulkActionMutation.mutate,
        bulkMarkAsSeen: (messageIds: number[], mailbox: string) =>
            bulkActionMutation.mutate({ messageIds, action: BulkActionType.SEEN, mailbox: mailbox }),
        bulkArchive: (messageIds: number[], mailbox: string) =>
            bulkActionMutation.mutate({ messageIds, action: BulkActionType.ARCHIVE, mailbox: mailbox }),
        bulkFavorite: (messageIds: number[], mailbox: string) =>
            bulkActionMutation.mutate({ messageIds, action: BulkActionType.FAVORITE, mailbox: mailbox }),
        bulkMoveToTrash: (messageIds: number[], mailbox: string) =>
            bulkActionMutation.mutate({ messageIds, action: BulkActionType.TRASH, mailbox: mailbox }),
        bulkDelete: (messageIds: number[], mailbox: string) =>
            bulkActionMutation.mutate({ messageIds, action: BulkActionType.DELETE, mailbox: mailbox }),
        bulkJunk: (messageIds: number[], mailbox: string) =>
            bulkActionMutation.mutate({ messageIds, action: BulkActionType.JUNK, mailbox: mailbox }),
        bulkUnfavorite: (messageIds: number[], mailbox: string) =>
            bulkActionMutation.mutate({ messageIds, action: BulkActionType.UNFAVORITE, mailbox: mailbox }),
        bulkUnarchive: (messageIds: number[], mailbox: string) =>
            bulkActionMutation.mutate({ messageIds, action: BulkActionType.UNARCHIVE, mailbox: mailbox }),
        bulkRestore: (messageIds: number[], mailbox: string) =>
            bulkActionMutation.mutate({ messageIds, action: BulkActionType.RESTORE, mailbox: mailbox }),

        // Single actions (keeping for backward compatibility)
        markAsSeen: markAsSeenMutation.mutate,
        archive: archiveMutation.mutate,
        favorite: favoriteMutation.mutate,
        moveToTrash: moveToTrashMutation.mutate,
        deletePermanently: deletePermanentlyMutation.mutate,
        sendEmail: sendEmailMutation.mutate,
        updateDraft: updateDraftMutation.mutate,
        deleteDraft: deleteDraftMutation.mutate,
        sendDraft: sendDraftMutation.mutate,
        unfavorite: unfavoriteMutation.mutate,
        unarchive: unarchiveMutation.mutate,
        restore: restoreMutation.mutate,
        isLoading,
    };
}; 