// Copyright (c) 2025, Huawei Technologies Co., Ltd.
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0  (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { invoke } from '@tauri-apps/api/core';
import { useCleanup, useI18n, useMessage } from 'hooks';
import { useAtom, useSetAtom } from 'jotai';
import { toast } from 'sonner';
import {
    dynamicVisibleAtom,
    loadingAtom,
    modelPathAtom,
    fsgVisibleAtom,
    translateAtom,
    useSelectionHistory,
    useZoom,
    currentGraphAtom,
    graphTreeAtom,
    fsgPanelVisibleAtom,
    dynamicNodesAtom,
    showThumbnailAtom,
    graphDataAtom,
    expandGraphDataAtom,
} from 'stores';
import { useRecentProjectStorage } from 'stores/useRecentProjectStorage';
import { ModelType } from 'types/enum';

type LayoutNewPath = (path: string | null) => Promise<void>

export const useNewPathForLayout = (): LayoutNewPath => {
    const [modelPath, setModelPath] = useAtom(modelPathAtom);
    const history = useSelectionHistory();
    const setCurrentGraph = useSetAtom(currentGraphAtom);
    const setGraphTree = useSetAtom(graphTreeAtom);
    const setGraphData = useSetAtom(graphDataAtom);
    const setDynamicVisible = useSetAtom(dynamicVisibleAtom);
    const setDynamicNodes = useSetAtom(dynamicNodesAtom);
    const setFsgPanelVisible = useSetAtom(fsgPanelVisibleAtom);
    const setFsgsVisible = useSetAtom(fsgVisibleAtom);
    const setShowThumbnail = useSetAtom(showThumbnailAtom);
    const setTranslate = useSetAtom(translateAtom);
    const setExpandGraphData = useSetAtom(expandGraphDataAtom);
    const [, , , resetZoom] = useZoom();
    const setLoading = useSetAtom(loadingAtom);
    const { recentProjCacheAdd } = useRecentProjectStorage();
    const t = useI18n();
    const { error } = useMessage();
    const cleanup = useCleanup();

    return async (path: string | null) => {
        if (!path || path === modelPath) { return; }
        setLoading(true);
        const start = performance.now();

        try {
            await invoke<LayoutRet>('check_path', { path });
            setFsgPanelVisible(false);
            history.clear();
            setCurrentGraph({ children: [], name: '', paths: [], model_type: ModelType.Unsupported });
            setGraphData({});
            setDynamicVisible(false);
            setDynamicNodes(null);
            setFsgsVisible(false);
            setShowThumbnail(false);
            setExpandGraphData({});
        } catch (err) {
            error(err as RequestError);
            setLoading(false);
            return;
        }

        try {
            const res = await invoke<LayoutRet>('layout_bin', { path });
            if (res !== null) {
                setModelPath(path);
                setCurrentGraph(res);
                setGraphTree(res);
                recentProjCacheAdd(path);

                resetZoom();
                setTranslate({ x: 0, y: 0 });
            }
        } catch (err) {
            error(err as RequestError);
            cleanup();
            setLoading(false);
            return;
        }
        toast.success(t('parseAndTransfer', { time: Math.round(performance.now() - start) }), {
            richColors: true,
            closeButton: true
        });
    };
};