import React from 'react';
import cookie from 'react-cookies';
import superagent from 'superagent';
import DarkReader from 'react-darkreader';

import { Container, Menu, Segment, Grid, Header, Image, Icon, Button, Form, Divider, Responsive, Input, Label } from 'semantic-ui-react'

export default class ArdaWrapper extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoggedIn: false,
            dropdownMenuStyle: {
                display: "none"
            },
            accessPolicies: []
        };
    }

    componentDidMount() {
        if (cookie.load("accessToken")) {
            this.setState({
                isLoggedIn: true,
                username: cookie.load('username'),
                accessToken: cookie.load('accessToken')
            });

            // Fetch user's access policies
            this.fetchAccessPolicies();
        } else {
            this.setState({
                isLoggedIn: false,
                username: null,
                accessToken: null
            });

            if (window.location.pathname !== "/login") {
                window.location.href = "/login";
            }
        }
    }

    async fetchAccessPolicies() {
        try {
            const res = await superagent.get('/api/admin/profile').accept('json');
            const account = res.body;
            this.setState({
                accessPolicies: account.accessPolicies || []
            }, () => {
                // After access policies are loaded, redirect factory users if on homepage
                this.redirectFactoryUsers();
            });
        } catch (e) {
            console.error('Failed to fetch access policies:', e);
        }
    }

    isFactoryUser() {
        const { accessPolicies = [] } = this.state;
        const adminRoles = ["SuperUser", "Admin", "Moderator"];
        const factoryRoles = ["Fabricator", "Inventory", "FabricatorAdmin"];

        // Check if user has any factory roles but no admin roles
        const hasFactoryRole = factoryRoles.some(role => accessPolicies.includes(role));
        const hasAdminRole = adminRoles.some(role => accessPolicies.includes(role));

        return hasFactoryRole && !hasAdminRole;
    }

    redirectFactoryUsers() {
        // Only redirect if user is on the homepage
        if (window.location.pathname === "/" && this.isFactoryUser()) {
            window.location.href = "/shop/orders?origin=Shopify";
        }
    }

    getVisibleMenuItems() {
        const { accessPolicies = [] } = this.state;

        // Define all possible menu items with their required access policies
        const allMenuItems = [
            { href: "/", label: "Rooms", roles: ["Moderator", "Admin", "SuperUser"] },
            { href: "/rooms/environments", label: "Environments", roles: ["Moderator", "Admin", "SuperUser"] },
            { href: "/cinema", label: "Movies+TV", roles: ["Moderator", "Admin", "SuperUser"] },
            { href: "/network", label: "Network", roles: ["Moderator", "Admin", "SuperUser"] },
            { href: "/apps", label: "Apps", roles: ["Moderator", "Admin", "SuperUser"] },
            { href: "/accounts", label: "Accounts", roles: ["Moderator", "Admin", "SuperUser", "FabricatorAdmin"] },
            { href: "/shop/orders?origin=Shopify", label: "BigOrders", roles: ["Moderator", "Admin", "SuperUser", "Fabricator", "Inventory", "FabricatorAdmin"] },
            { href: "/fabricator", label: "Fabricator", roles: ["Moderator", "Admin", "SuperUser", "Fabricator", "Inventory", "FabricatorAdmin"] },
            { href: "/inventory", label: "BigInventory", roles: ["Moderator", "Admin", "SuperUser", "Fabricator", "Inventory", "FabricatorAdmin"] },
            { href: "/shipper", label: "BigShipper", roles: ["Moderator", "Admin", "SuperUser", "Fabricator", "Inventory", "FabricatorAdmin"] },
            { href: "/experimental", label: "Experimental", roles: ["Admin", "SuperUser", "FabricatorAdmin"] },
            { href: "/developers", label: "Developers", roles: ["Admin", "Moderator", "Fabricator", "SuperUser"] }
        ];

        // Filter menu items based on user's access policies
        return allMenuItems.filter(item =>
            item.roles.some(role => accessPolicies.includes(role))
        );
    }

    handleToggleDropdownMenu() {
        let newState = Object.assign({}, this.state);
        if (newState.dropdownMenuStyle.display === "none") {
            newState.dropdownMenuStyle = { display: "flex" };
        } else {
            newState.dropdownMenuStyle = { display: "none" };
        }

        this.setState(newState);
    }

    render() {
        let isMainNetwork = false;
        let networkName = "main"
        let bannerColor = "black";

        if (window) {
            if (window.location.hostname === "localhost" || window.location.hostname.startsWith("dev-")) {
                networkName = "dev";
                bannerColor = "pink";
            }
            else if (window.location.hostname.startsWith("test-")) {
                networkName = "test";
                bannerColor = "orange";
            } else {
                isMainNetwork = true;
            }
        }

        const visibleMenuItems = this.getVisibleMenuItems();

        let leftMenu = (
            <Menu.Menu stackable={1} position='left'>
                {visibleMenuItems.map(item => (
                    <Menu.Item key={item.href} href={item.href}>
                        {item.label}
                    </Menu.Item>
                ))}
            </Menu.Menu>
        );

        let defaultDarken = true;
        const isDarkModeEnabled = localStorage.getItem('darkModeEnabled');
        if (isDarkModeEnabled === null) {
            defaultDarken = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)');
        } else {
            defaultDarken = isDarkModeEnabled === 'true';
        }

        let rightMenu = (
            <Menu.Menu stackable={1} position='right'>
                <Menu.Item><DarkReader defaultDarken={defaultDarken}
                    theme={{
                        brightness: 100,
                        contrast: 95,
                        sepia: 10,
                    }} onChange={isDark => {
                        if (isDark) {
                            localStorage.setItem('darkModeEnabled', 'true');
                        } else {
                            localStorage.setItem('darkModeEnabled', 'false');
                        }
                    }} /></Menu.Item>
                <Menu.Item><Icon name='connectdevelop' /><strong>{networkName}</strong></Menu.Item>
                <Menu.Item><Icon name='user' /><strong>{this.state.username}</strong></Menu.Item>
                <Menu.Item href="/logout">Logout</Menu.Item>
            </Menu.Menu>
        );

        let mobileRightMenu = (
            <Menu.Menu position="right">
                <Menu.Item>
                    <Button
                        basic
                        inverted
                        icon
                        toggle
                        onClick={this.handleToggleDropdownMenu}
                    >
                        <Icon name="content" />
                    </Button>
                </Menu.Item>
            </Menu.Menu>
        );

        let mobileLeftMenu = (
            <Menu
                borderless
                fluid
                inverted
                vertical
                style={this.state.dropdownMenuStyle}
            >
                {visibleMenuItems.map(item => (
                    <Menu.Item key={item.href} href={item.href}>
                        {item.label}
                    </Menu.Item>
                ))}
                <Divider fitted />
                <Menu.Item>
                    <Input placeholder="Search..." size="small" />
                </Menu.Item>
            </Menu>
        );

        return (
            <div>
                <div className="topMenu">
                    <Grid padded className="tablet computer only">
                        <Menu borderless inverted color={bannerColor} fixed="top">
                            <Menu.Item height="40px"><Image href='/' size='small' src='/images/bigscreen_logo.png' /></Menu.Item>
                            {this.state.isLoggedIn && leftMenu}
                            {this.state.isLoggedIn && rightMenu}
                        </Menu>
                    </Grid>
                    <Grid padded className="mobile only">
                        <Menu borderless inverted fluid fixed="top">
                            <Menu.Item height="40px"><Image height="40px" href='/' size='small' src='/images/bigscreen_logo_black_no_margin.png' /></Menu.Item>
                            {this.state.isLoggedIn && mobileRightMenu}
                            {this.state.isLoggedIn && mobileLeftMenu}
                        </Menu>
                    </Grid>
                </div>
                <div style={{ marginTop: "40px" }}>
                    {this.props.children}
                </div>
            </div>
        );
    }
}
