import {
    useCreateBackupMutation,
    useDeleteBackupMutation,
    useGetBackupsQuery, useUploadBackupMutation
} from "../../../../../Api/backupsApi.js";
import {useDispatch} from "react-redux";
import {notification} from "antd";
import {baseQueryWithAuth} from "../../../../../Api/baseQuery.js";
import {useState} from "react";


const useBackupManageTab = () => {
    const dispatch = useDispatch();
    const {data: backups, isLoading: isLoadingBackups, isError: isErrorBackups} = useGetBackupsQuery(undefined, {
        pollingInterval: 60000,
    });
    const [createBackup, {isLoading: isCreatingBackup}] = useCreateBackupMutation();
    const [deleteBackup, {isLoading: isDeletingBackup}] = useDeleteBackupMutation();
    const [uploadBackup, {isLoading: isUploadingBackup}] = useUploadBackupMutation();

    const [isDownloadingBackup, setDownloadingFiles] = useState(false);

    const createBackupHandler = async () => {
        try {
            await createBackup().unwrap();
            notification.success({
                message: "Успех",
                description: "Резервная копия успешно создана",
                placement: "topRight",
            });
        } catch (e) {
            notification.error({
                message: "Ошибка",
                description: e?.data?.detail || "Не удалось создать резервную копию",
                placement: "topRight",
            });
        }
    };

    const downloadBackupHandler = async (backupId, fileName) => {
        try {
            setDownloadingFiles(true);
            const {url, ...options} = await baseQueryWithAuth(
                {
                    url: `/backups/${backupId}/`,
                    method: 'GET',
                    credentials: 'include',
                },
                {},
                {}
            );

            const response = await fetch(url, {
                ...options,
                method: 'GET',
                credentials: 'include',
            });

            if (!response.ok) {
                notification.error({
                    message: "Ошибка при скачивании файла",
                    description: "Не удалось загрузить файл.",
                    placement: "topRight",
                });
            }

            const blob = await response.blob();
            const downloadUrl = window.URL.createObjectURL(blob);
            const link = document.createElement("a");
            link.href = downloadUrl;
            link.setAttribute("download", fileName || "file");
            document.body.appendChild(link);
            link.click();
            link.remove();
            window.URL.revokeObjectURL(downloadUrl);
            setDownloadingFiles(false);
        } catch (e) {
            console.log(e)
            notification.error({
                message: "Ошибка",
                description: e?.data?.detail || "Не удалось загрузить резервную копию",
                placement: "topRight",
            });
        }
    };

    const deleteBackupHandler = async (backupId) => {
        try {
            await deleteBackup(backupId).unwrap();
            notification.success({
                message: "Успех",
                description: "Резервная копия успешно удалена",
                placement: "topRight",
            });
        } catch (e) {
            notification.error({
                message: "Ошибка",
                description: e?.data?.detail || "Не удалось удалить резервную копию",
                placement: "topRight",
            });
        }
    };

    const uploadBackupHandler = async (file) => {
        try {
            if (!file || !(file instanceof File)) {
                notification.error({
                    message: "Ошибка",
                    description: "Файл не выбран",
                    placement: "topRight",
                });
                return;
            }
            await uploadBackup(file).unwrap();
            notification.success({
                message: "Успех",
                description: "Резервная копия успешно загружена",
                placement: "topRight",
            });
        } catch (e) {
            notification.error({
                message: "Ошибка",
                description: e.message || e?.data?.detail || "Не удалось загрузить резервную копию",
                placement: "topRight",
            });
        }
    };

    return {
        backups,
        isLoadingBackups,
        isErrorBackups,
        isCreatingBackup,
        isDownloadingBackup,
        isDeletingBackup,
        isUploadingBackup,
        createBackupHandler,
        downloadBackupHandler,
        deleteBackupHandler,
        uploadBackupHandler,
    }
};

export default useBackupManageTab;