import React, { createContext, useContext, useState, useEffect } from 'react';
import { Routes, Route } from 'react-router-dom';
import Dashboard from './pages/Dashboard';
import Orders from './pages/Orders';
import OrderDetails from './pages/OrderDetails';
import OrderEditor from './pages/OrderEditor';
import BulkOrderEditor from './pages/BulkOrderEditor';
import Products from './pages/Products';
import ProductEditor from './pages/ProductEditor';
import BulkProductEditor from './pages/BulkProductEditor';
import AttributeTerms from './pages/AttributeTerms';
import Settings from './pages/Settings';
import Customers from './pages/Customers';
import CustomerEditor from './pages/CustomerEditor';
import Layout from './components/Layout';
import './styles/app.scss';
import './styles/layout.scss';
import './styles/dashboard.scss';

// Create Toast Context
const ToastContext = createContext();

export const useToast = () => {
    const context = useContext(ToastContext);
    if (!context) {
        throw new Error('useToast must be used within a ToastProvider');
    }
    return context;
};

const ToastProvider = ({ children }) => {
    const [toast, setToast] = useState({
        open: false,
        message: '',
        severity: 'info'
    });

    const showToast = (message, severity = 'info') => {
        setToast({
            open: true,
            message,
            severity
        });
    };

    const showSuccess = (message) => showToast(message, 'success');
    const showError = (message) => showToast(message, 'error');
    const showWarning = (message) => showToast(message, 'warning');
    const showInfo = (message) => showToast(message, 'info');

    const hideToast = () => {
        setToast(prev => ({ ...prev, open: false }));
    };

    useEffect(() => {
        if (toast.open) {
            const timer = setTimeout(() => {
                hideToast();
            }, 4000);
            return () => clearTimeout(timer);
        }
    }, [toast.open]);

    return (
        <ToastContext.Provider value={{ showToast, showSuccess, showError, showWarning, showInfo }}>
            {children}
            {toast.open && (
                <div className={`toast toast-${toast.severity}`}>
                    <div className="toast-content">
                        <span className="toast-message">{toast.message}</span>
                        <button className="toast-close" onClick={hideToast}>×</button>
                    </div>
                </div>
            )}
        </ToastContext.Provider>
    );
};

const App = () => {
    const [frontendSettings, setFrontendSettings] = useState(null);
    const [loading, setLoading] = useState(true);
    const isFrontend = !window.location.pathname.includes('wp-admin');

    useEffect(() => {
        // Load frontend settings if on frontend
        if (isFrontend) {
            fetch(window.shopExplorerData?.apiUrl + '/frontend-settings', {
                headers: {
                    'X-WP-Nonce': window.shopExplorerData?.nonce
                }
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    setFrontendSettings(data.settings);
                }
                setLoading(false);
            })
            .catch(err => {
                console.error('Failed to load frontend settings:', err);
                setLoading(false);
            });
        } else {
            setLoading(false);
        }
    }, [isFrontend]);

    if (loading && isFrontend) {
        return (
            <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
                <div>Loading...</div>
            </div>
        );
    }

    // Redirect component for disabled features
    const RedirectToDashboard = () => {
        useEffect(() => {
            window.location.hash = '#/';
        }, []);
        return <Dashboard />;
    };

    return (
        <ToastProvider>
            <Layout>
                <Routes>
                    <Route path="/" element={<Dashboard />} />
                    <Route 
                        path="/orders" 
                        element={
                            !isFrontend || frontendSettings?.orders_management?.enabled 
                                ? <Orders /> 
                                : <RedirectToDashboard />
                        } 
                    />
                    <Route 
                        path="/orders/view/:id" 
                        element={
                            !isFrontend || frontendSettings?.orders_management?.enabled 
                                ? <OrderDetails /> 
                                : <RedirectToDashboard />
                        } 
                    />
                    <Route 
                        path="/orders/add" 
                        element={
                            !isFrontend || frontendSettings?.orders_management?.enabled 
                                ? <OrderEditor /> 
                                : <RedirectToDashboard />
                        } 
                    />
                    <Route 
                        path="/orders/edit/:id" 
                        element={
                            !isFrontend || frontendSettings?.orders_management?.enabled 
                                ? <OrderEditor /> 
                                : <RedirectToDashboard />
                        } 
                    />
                    <Route 
                        path="/orders/bulk-edit" 
                        element={
                            !isFrontend || frontendSettings?.orders_management?.enabled 
                                ? <BulkOrderEditor /> 
                                : <RedirectToDashboard />
                        } 
                    />
                    <Route 
                        path="/products" 
                        element={
                            !isFrontend || frontendSettings?.products_management?.enabled 
                                ? <Products /> 
                                : <RedirectToDashboard />
                        } 
                    />
                    <Route 
                        path="/products/add" 
                        element={
                            !isFrontend || frontendSettings?.products_management?.enabled 
                                ? <ProductEditor /> 
                                : <RedirectToDashboard />
                        } 
                    />
                    <Route 
                        path="/products/edit/:id" 
                        element={
                            !isFrontend || frontendSettings?.products_management?.enabled 
                                ? <ProductEditor /> 
                                : <RedirectToDashboard />
                        } 
                    />
                    <Route 
                        path="/products/bulk-edit" 
                        element={
                            !isFrontend || frontendSettings?.products_management?.enabled 
                                ? <BulkProductEditor /> 
                                : <RedirectToDashboard />
                        } 
                    />
                    <Route 
                        path="/attributes/:attributeId/terms" 
                        element={
                            !isFrontend || frontendSettings?.products_management?.enabled 
                                ? <AttributeTerms /> 
                                : <RedirectToDashboard />
                        } 
                    />
                    <Route 
                        path="/customers" 
                        element={
                            !isFrontend || frontendSettings?.customer_management?.enabled 
                                ? <Customers /> 
                                : <RedirectToDashboard />
                        } 
                    />
                    <Route 
                        path="/customers/add" 
                        element={
                            !isFrontend || frontendSettings?.customer_management?.enabled 
                                ? <CustomerEditor /> 
                                : <RedirectToDashboard />
                        } 
                    />
                    <Route 
                        path="/customers/edit/:id" 
                        element={
                            !isFrontend || frontendSettings?.customer_management?.enabled 
                                ? <CustomerEditor /> 
                                : <RedirectToDashboard />
                        } 
                    />
                    <Route 
                        path="/settings" 
                        element={!isFrontend ? <Settings /> : <RedirectToDashboard />} 
                    />
                </Routes>
            </Layout>
        </ToastProvider>
    );
};

export default App; 