import React, {useState, useEffect} from "react";
import WidgetHeader from "../../components/widget_header/widget_header";
import './assembly_editor.css'
import WorkspaceHeader from "../../components/workspace_header/workspace_header";
import EmptyView from "../../components/EmptyView/empty_view";
import AssemblyTree from "../../components/AssemblyTree/AssemblyTree";
import BreadCrumps from "../../components/BreadCrumps/BreadCrumps";
import ImageTable from "../../components/ImageTable/ImageTable";
import exampleImg from '../../assets/exampleImg.jpg'
import { useQuery, useMutation, QueryClient } from '@tanstack/react-query';
import { DndProvider, useDrop } from 'react-dnd'
import { HTML5Backend } from 'react-dnd-html5-backend'

class apiAdapter {
    static #findNodeById(items, targetId) {
        // Проверяем корневой элемент assembly
        if (items.id === targetId) {
            return items;
        }
        
        // Рекурсивно ищем в детях
        if (items.children) {
            for (const item of items.children) {
                if (item.id === targetId) {
                    return item;
                }
                
                const foundInChildren = this.#findNodeById(item, targetId);
                if (foundInChildren) {
                    return foundInChildren;
                }
            }
        }
        
        return null;
    }

    static dataForTreeView(apiData) {
        if (!apiData || !apiData.assembly) return null;
        
        const transformNode = (node) => {
            return {
                id: node.id,
                name: node.name,
                code: node.code,
                image: node.image,
                children: node.children ? node.children.map(transformNode) : []
            };
        };
        
        const assembly = apiData.assembly;
        const result = {
            id: assembly.id,
            name: assembly.name,
            code: assembly.code,
            image: assembly.image,
            children: assembly.children ? assembly.children.map(transformNode) : []
        };
        
        return result;
    }

    static dataForHeader(apiData, targetId) {
        if (!apiData || !apiData.assembly) return null;
        
        const foundNode = this.#findNodeById(apiData.assembly, targetId);
        if (foundNode) {
            return {
                name: foundNode.name,
                code: foundNode.code
            };
        }
        
        return null;
    }

    static dataForTable(apiData, targetId) {
        if (!apiData || !apiData.assembly) return [];
        // Находим элемент по targetId
        const findElement = (items) => {
            for (const item of items) {
                if (item.id === targetId) return item;
                if (item.children) {
                    const found = findElement(item.children);
                    if (found) return found;
                }
            }
            return null;
        };

        let targetElement = null;
        
        // Проверяем корневой элемент
        if (apiData.assembly && apiData.assembly.id === targetId) {
            targetElement = apiData.assembly;
        } else if (apiData.assembly && apiData.assembly.children) {
            targetElement = findElement(apiData.assembly.children);
        }

        // Если элемент не найден или нет детей, возвращаем пустой массив
        if (!targetElement || !targetElement.children || targetElement.children.length === 0) {
            return [];
        }

        // Преобразуем детей первого уровня в нужный формат
        return targetElement.children.map((child, index) => ({
            name: child.name,
            position: (index + 1).toString(),
            code: child.code || ""
        }));
    }

    static dataForImage(apiData, targetId) {
        if (!apiData || !apiData.assembly) return null;
        
        const foundNode = this.#findNodeById(apiData.assembly, targetId);
        if (foundNode) {
            return {
                image: foundNode.image
            };
        }
        
        return null;
    }
}


const locationData = [
    {
        "name": "Эта",
        "link": "",
    },
    {
        "name": "Навигация",
        "link": "",
    },
    {
        "name": "Пока",
        "link": "",
    },
    {
        "name": "Не",
        "link": "",
    },
    {
        "name": "Функциональна",
        "link": "",
    },
]





const AssemblyEditor = ({queryClient}) => {
    const[isActive, setActive] = useState(() => {
    const saved = localStorage.getItem('isActive');
    

    return saved ? JSON.parse(saved) : false;
    });

    const [selectedNodeId, setSelectedNodeId] = useState(() => {
        const saved = localStorage.getItem('selectedNodeId');
        return saved ? parseInt(saved) : null;
    });
    const [assemblyId, setAssemblyId] = useState(() => {
        const saved = localStorage.getItem('assemblyId');
        return saved ? parseInt(saved) : null;
    })

    // Информация о выбранной сборке в дереве
    const [selectedImg, setImage] = useState(() => {
        const saved = localStorage.getItem('selectedImage');
        return saved ? JSON.parse(saved) : '';
    });
    const [selectedTableData, setTableData] = useState(() => {
        const saved = localStorage.getItem('selectedTableData');
        return saved ? JSON.parse(saved) : [];
    });
    const [selectedHeaderData, setHeaderData] = useState(() => {
        const saved = localStorage.getItem('selectedHeaderData');
        return saved ? JSON.parse(saved) : { name: '', code: '' };
    });

    const {data, isLoading, error} = useQuery({
        queryKey: ['assembly'],
        queryFn: () => fetch(`http://127.0.0.1:5000/api/v1/assembly/${assemblyId}`)
            .then(res => {
                if (!res.ok) {
                    throw new Error('Network response was not ok');
                }
                return res.json();
            }),
        
        onError: (error) => {
        console.error('Error fetching assembly:', error);
        },
        staleTime: 5000,
        enabled: isActive,


    });

    /*
    const [imageData, isLoadingImage, errorImage] = useQuery({
        queryKey: ['assembly_image'],
        queryFn: () => fetch(`http://127.0.0.1:5000/api/v1/images/${selectedImg}`)
            .then(res => {
                if (!res.ok) {
                    throw new Error('Network response was not ok');
                }
                return res.json();
            }), 
        staleTime: 5000,
        enabled: isActive,

    }); */

    useEffect(() => {
    localStorage.setItem('isActive', JSON.stringify(isActive));
    }, [isActive]);
        function checkActive() {
            if(localStorage.getItem('isActive')) {
                return localStorage.getItem('isActive');
            }
            return false;
        }

    

    function switchActive() {
        setActive(!isActive);
        JSON.stringify(isActive);
        localStorage.setItem('isActive', isActive);
        
    }

    useEffect(() => {
        if (data?.assembly && isActive) {
            const rootId = data.assembly.id;
            // Только если нет сохранённого ID, используем корневой
            const nodeIdToUse = selectedNodeId || rootId;
            setSelectedNodeId(nodeIdToUse);
            
            // Загружаем данные только если они не были загружены ранее
            if (!localStorage.getItem('selectedHeaderData')) {
                const headerData = apiAdapter.dataForHeader(data, nodeIdToUse) || { name: '', code: '' };
                setHeaderData(headerData);
            }
            
            if (!localStorage.getItem('selectedTableData')) {
                const tableData = apiAdapter.dataForTable(data, nodeIdToUse) || [];
                setTableData(tableData);
            }
            
            localStorage.setItem('assemblyId', JSON.stringify(assemblyId));
        }
    }, [data, isActive]);


    function openAssembly(item) {
        setActive(true);
        setAssemblyId(item.fileId);
        
    }

    const [{ isOver }, drop] = useDrop(() => ({
            accept: 'FILE',
            drop: (item) => openAssembly(item),
            collect: (monitor) => ({
                isOver: monitor.isOver(),
            }),
        }));

    const selectNode = (id) => {
        setSelectedNodeId(id);
        if (data) {
            const headerData = apiAdapter.dataForHeader(data, id) || { name: '', code: '' };
            const tableData = apiAdapter.dataForTable(data, id) || [];
            const imageData = apiAdapter.dataForImage(data, id) || null;
            setHeaderData(headerData);
            setTableData(tableData);
            setImage(imageData)
            localStorage.setItem('selectedNodeId', JSON.stringify(id));
            localStorage.setItem('selectedTableData', JSON.stringify(tableData));
            localStorage.setItem('selectedHeaderData', JSON.stringify(headerData));
            localStorage.setItem('selectedImage', JSON.stringify(imageData));
        }
    };

    
 
    return (
        
            <div style={{
                width: '100%',
                position: 'relative',
            }}
            ref={drop}>
                <div style={{
                    width: '100%',
                    height: '92vh',
                    padding: '32px',
                    visibility: `${isActive ? 'hidden' : 'visible'}`,
                    position: 'absolute',
                }}>
                    <EmptyView text={'Перетащите сборку для начала работы'} display={isActive}/>
                </div>


                <div style={{
                    visibility: `${isActive ? 'visible' : 'hidden'}`,
                    position: 'absolute',
                    width: '100%',
                    height: '94vh',
                    display: 'flex',
                    flexDirection: 'row',
                }}>
                    <div>

                        <AssemblyTree 
                            data={apiAdapter.dataForTreeView(data)} 
                            isActive={isActive}
                            onNodeSelect={(id) => selectNode(id)}
                            assemblyId={selectedNodeId}/>
                    </div>
                    <div style={{width:'100%', margin: '8px 24px'}}>
                        <div style={{display: 'flex', flexDirection: 'row',}}>
                            <BreadCrumps location={locationData}/>
                            <button className="close-workspace" onClick={switchActive}><i className="fas fa-window-close" 
                            style={{float: 'right'}}/></button>
                        </div>
                        <ImageTable
                            id = {selectedNodeId} 
                            img={selectedImg}
                            tableData={selectedTableData} 
                            headerData={selectedHeaderData} 
                            queryClient={queryClient}
                            />
                    </div>
                    
                </div>
                

            </div>

        
        
    );
};

export default AssemblyEditor;

this code works fine

but when i delete comments on this commented useQuery, it returns error 
Uncaught runtime errors:
×
ERROR
object is not iterable (cannot read property Symbol(Symbol.iterator))
TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))