import 'package:flutter/material.dart';
import '../widgets/bottom_navigation.dart';
import '../widgets/mobile_bottom_navigation.dart';

class MainLayout extends StatefulWidget {
  final Widget child;
  final String? currentRoute;

  const MainLayout({super.key, required this.child, this.currentRoute});

  @override
  _MainLayoutState createState() => _MainLayoutState();
}

class _MainLayoutState extends State<MainLayout> {
  int _selectedIndex = 0;

  @override
  void initState() {
    super.initState();
    _selectedIndex = _getIndexFromRoute(widget.currentRoute ?? '/tables');
  }

  int _getIndexFromRoute(String route) {
    switch (route) {
      case '/tables':
        return 0;
      case '/commandes':
      case '/orders':
        return 1;
      case '/categories':
        return 2;
      case '/menu':
        return 3;
      case '/plats':
        return 4;
      case '/encaissement':
        return 5;
      case '/historique':
        return 6;
      case '/information':
        return 7;
      case '/Setting':
        return 8;
      default:
        return 0;
    }
  }

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });

    String route;
    switch (index) {
      case 0:
        route = '/tables';
        break;
      case 1:
        route = '/commandes';
        break;
      case 2:
        route = '/categories';
        break;
      case 3:
        route = '/menu';
        break;
      case 4:
        route = '/plats';
        break;
      case 5:
        route = '/encaissement';
        break;
      case 6:
        route = '/historique';
        break;
      case 7:
        route = '/information';
        break;
      case 8:
        route = '/Setting';
        break;
      default:
        route = '/tables';
    }

    if (route != widget.currentRoute) {
      Navigator.pushReplacementNamed(context, route);
    }
  }

  @override
  Widget build(BuildContext context) {
    final isDesktop = MediaQuery.of(context).size.width > 600;

    return Scaffold(
      body: Column(
        children: [
          Expanded(child: widget.child),
          // Show desktop navigation on larger screens
          if (isDesktop)
            AppBottomNavigation(
              selectedIndex: _selectedIndex,
              onItemTapped: _onItemTapped,
            ),
        ],
      ),
      // Show mobile navigation on smaller screens
      bottomNavigationBar:
          isDesktop
              ? null
              : MobileBottomNavigation(
                currentRoute: widget.currentRoute ?? '/tables',
                selectedIndex: _selectedIndex,
                onItemTapped: _onItemTapped,
              ),
    );
  }
}
