import React, {Component} from 'react';
import {connect} from "react-redux";
import {addProductLabels, addProductsWithIds} from './helpers/ProductsManager';
import "react-datepicker/dist/react-datepicker.css";
import {Tree} from './Tree';
import {LegacyDashboard} from "@/LegacyDashboard";
import {TreeDashboard} from "@/TreeDashboard";
import {atomsStore, DocumentDimensionsAtom, HorizontalOffsetAtom, ModelAtom, VerticalOffsetAtom} from "@/tree/atoms";
import {CouponsPlus} from "@/globals";


class Dashboard extends Component
{
    constructor() 
    {
        super();
        $('body').attr('id', 'coupons-plus-admin');

        addProductLabels(CouponsPlus.products.default.labels);
        addProductsWithIds(CouponsPlus.products.default.idsWithVariations);
        this.setGlobals()
        this.setModel()
    }

    setGlobals() 
    {
        /**
         * Because countries and states are such a big data, we'll just map 'em once and add it in a global variable.
         */
         const mapTerritory = territoryType => {
            let countriesOrStates = (territoryType === 'country'?window?.CouponsPlus?.places?.countries :window.CouponsPlus?.places?.states) ?? {};
            return Object.keys(countriesOrStates)
                         .map(code => ({value: code, label: countriesOrStates[code]}))    
         }

        window.CouponsPlus.mappedTerritories = {
            country: mapTerritory('country'),
            state: mapTerritory('state')
         }
    }

    componentDidMount() {
        const adminMenu = document.querySelector('#adminmenu');
        const leftBarWidth = adminMenu?.getBoundingClientRect()?.width || 0
        const topBarHeight = document.querySelector('#wpadminbar')?.getBoundingClientRect()?.height || 0

        atomsStore.set(VerticalOffsetAtom, topBarHeight);
        atomsStore.set(HorizontalOffsetAtom, leftBarWidth);
        atomsStore.set(DocumentDimensionsAtom, document.documentElement.getBoundingClientRect())

        this.adminSidebarResizeObserver = new ResizeObserver(entries => {
            for (const entry of entries) {
                if (entry.target === adminMenu) {
                    atomsStore.set(HorizontalOffsetAtom, entry.contentRect.width);
                }
            }
        });

        this.documentResizeObserver = new ResizeObserver(entries => {
            for (const entry of entries) {
                if (entry.target === document.documentElement) {
                    atomsStore.set(DocumentDimensionsAtom, {
                        width: entry.contentRect.width,
                        height: entry.contentRect.height
                    });
                }
            }
        });

        this.adminSidebarResizeObserver.observe(adminMenu);
        this.documentResizeObserver.observe(document.documentElement);

        this.unsubscribeModelAtom = atomsStore.sub(ModelAtom, () => {
            this.forceUpdate();
        });
    }

    componentWillUnmount() {
        if (this.adminSidebarResizeObserver) {
            this.adminSidebarResizeObserver.disconnect();
        }
        if (this.documentResizeObserver) {
            this.documentResizeObserver.disconnect();
        }
        if (this.unsubscribeModelAtom) {
            this.unsubscribeModelAtom();
        }
    }

    render() 
    {
        if (atomsStore.get(ModelAtom) === 'tree') {
            return <TreeDashboard />
        }

        return <LegacyDashboard />
    }

    setModel() {
        atomsStore.set(ModelAtom, CouponsPlus.state.model)
    }
}

export default connect(Dashboard.mapStateToProps, {})(Dashboard);
