import { useEffect, useState } from "react";
import {
    ClientSchema,
    MarketplaceSchema,
    MarketplaceService,
    TaskService,
} from "../../../client";
import { notifications } from "../../../shared/lib/notifications.ts";
import { RootState, useAppDispatch } from "../../../redux/store.ts";
import { addTask } from "../../../features/tasksSlice.tsx";
import { useSelector } from "react-redux";

const useMarketplacesPageState = () => {
    const dispatch = useAppDispatch();
    const tasks = useSelector((state: RootState) => state.tasks.tasks);
    const [client, setClient] = useState<ClientSchema | undefined>();
    const [items, setItems] = useState<MarketplaceSchema[]>([]);
    const fetchMarketplaces = async () => {
        if (!client) return;
        MarketplaceService.getClientMarketplaces({
            requestBody: {
                clientId: client.id,
            },
        }).then(response => {
            setItems(response.marketplaces);
        });
    };

    const onCreate = (marketplace: MarketplaceSchema) => {
        MarketplaceService.createMarketplace({
            requestBody: {
                marketplace: {
                    ...marketplace,
                    clientId: marketplace.client.id,
                    baseMarketplaceKey: marketplace.baseMarketplace.key,
                },
            },
        }).then(async ({ ok, message }) => {
            notifications.guess(ok, { message });
            if (!ok) return;
            await fetchMarketplaces();
        });
    };
    const onDelete = (marketplace: MarketplaceSchema) => {
        MarketplaceService.deleteMarketplace({
            requestBody: {
                marketplaceId: marketplace.id,
            },
        }).then(async ({ ok, message }) => {
            notifications.guess(ok, { message });
            if (!ok) return;
            await fetchMarketplaces();
        });
    };
    const onChange = (marketplace: MarketplaceSchema) => {
        MarketplaceService.updateMarketplace({
            requestBody: {
                marketplace: marketplace,
            },
        }).then(async ({ ok, message }) => {
            notifications.guess(ok, { message });
            if (!ok) return;
            await fetchMarketplaces();
        });
    };

    const onSynchronize = (marketplace: MarketplaceSchema) => {
        const task = tasks.find(
            task => task.info.marketplaceId === marketplace.id
        );
        if (task) {
            notifications.error({
                title: "Ошибка",
                message: `Синхронизация маркетплейса ${marketplace.name} уже запущена`,
            });
            return;
        }
        TaskService.createSynchronizeMarketplaceTask({
            requestBody: {
                marketplaceId: marketplace.id,
            },
        }).then(({ taskId }) => {
            dispatch(
                addTask({
                    id: taskId,
                    config: {
                        onErrorData: {
                            title: "Ошибка",
                            message: `Ошибка синхронизации маркетплейса: ${marketplace.name}`,
                        },
                        onLoadingData: {
                            title: "Синхронизация",
                            message: `Синхронизация маркетплейса: ${marketplace.name}`,
                        },
                        onSuccessData: {
                            title: "Успех",
                            message: `Маркетплейс ${marketplace.name} успешно синхронизирован`,
                        },
                    },
                    info: {
                        marketplaceId: marketplace.id,
                    },
                })
            );
        });
    };
    useEffect(() => {
        fetchMarketplaces();
    }, [client]);
    return {
        client,
        setClient,
        items,
        onDelete,
        onChange,
        onCreate,
        onSynchronize,
    };
};
export default useMarketplacesPageState;
