import {
    useCreateBackupMutation,
    useDeleteBackupMutation,
    useGetBackupsQuery,
    useUploadBackupMutation,
    useRestoreBackupMutation,
} from "../../../../../Api/backupsApi.js";
import {notification} from "antd";
import {useState} from "react";
import CONFIG from "../../../../../Core/сonfig.js";


const useBackupManageTab = () => {
    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 token = localStorage.getItem('access_token');
            if (!token) {
                notification.error({
                    message: "Ошибка",
                    description: "Токен не найден",
                    placement: "topRight",
                });
                return;
            }

            const response = await fetch(`${CONFIG.BASE_URL}backups/${backupId}/file/`, {
                method: 'GET',
                credentials: 'include',
                headers: {
                    'Authorization': `Bearer ${token}`,
                },
            });

            if (!response.ok) {
                const errorText = await response.text();
                notification.error({
                    message: "Ошибка",
                    description: errorText || "Не удалось скачать резервную копию",
                    placement: "topRight",
                });
                return;
            }

            const contentType = response.headers.get('content-type');

            if (!contentType || (!contentType.includes('application/gzip') && !contentType.includes('application/zip'))) {
                const errorText = await response.text();
                notification.error({
                    message: "Ошибка",
                    description: errorText || "Не удалось скачать резервную копию",
                    placement: "topRight",
                });
                return;
            }

            const blob = await response.blob();
            const downloadUrl = window.URL.createObjectURL(blob);
            const link = document.createElement("a");
            link.href = downloadUrl;
            link.setAttribute("download", fileName || "backup.tar.gz");
            document.body.appendChild(link);
            link.click();
            link.remove();
            window.URL.revokeObjectURL(downloadUrl);
            notification.success({
                message: "Успех",
                description: "Резервная копия успешно скачана",
                placement: "topRight",
            });
        } catch (e) {
            console.error("Download error:", e); // Отладка
            notification.error({
                message: "Ошибка",
                description: e.message || "Не удалось скачать резервную копию",
                placement: "topRight",
            });
        } finally {
            setDownloadingFiles(false);
        }
    };

    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) {
            console.error("Upload error:", 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;