import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import '../api_client.dart';
import '../auth_storage.dart';
import 'home_screen.dart';
import 'services_screen.dart';
import 'shop_screen.dart';
import 'settings_screen.dart';
import 'orders_list_screen.dart';
import 'notifications_screen.dart';

class MainShellScreen extends StatefulWidget {
  const MainShellScreen({super.key});

  @override
  State<MainShellScreen> createState() => _MainShellScreenState();
}

class _MainShellScreenState extends State<MainShellScreen> {
  int _index = 0;
  int _orderCount = 0;
  final ValueNotifier<int> _homeRefreshTrigger = ValueNotifier(0);
  final ValueNotifier<int> _orderCountRefreshTrigger = ValueNotifier(0);
  late Dio _dio;

  void _onUnauthorized() {
    AuthStorage.clearToken();
    if (mounted) {
      Navigator.of(context).pushNamedAndRemoveUntil('/login', (r) => false);
    }
  }

  void _onOrderCreated() {
    setState(() => _index = 0);
    _homeRefreshTrigger.value++;
    _loadOrderCount();
  }

  @override
  void initState() {
    super.initState();
    _dio = createApiClient(_onUnauthorized);
    _orderCountRefreshTrigger.addListener(_loadOrderCount);
    _loadOrderCount();
  }

  @override
  void dispose() {
    _orderCountRefreshTrigger.removeListener(_loadOrderCount);
    _orderCountRefreshTrigger.dispose();
    _homeRefreshTrigger.dispose();
    super.dispose();
  }

  Future<void> _loadOrderCount() async {
    try {
      final r = await _dio.get('/api/orders', queryParameters: {'limit': 100});
      if (!mounted) return;
      final list = (r.data is Map && r.data['data'] is List) ? r.data['data'] as List : [];
      final count = list.where((o) {
        final status = (o is Map ? o['status'] : null)?.toString().toLowerCase() ?? '';
        return status != 'failed' && status != 'cancelled' && status != 'delivered';
      }).length;
      setState(() => _orderCount = count);
    } catch (_) {
      if (mounted) setState(() => _orderCount = 0);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_title),
        actions: [
          if (_index == 0) ...[
            IconButton(
              icon: Badge(
                isLabelVisible: _orderCount > 0,
                label: Text('$_orderCount', style: const TextStyle(fontSize: 10)),
                child: const Icon(Icons.shopping_bag_outlined),
              ),
              onPressed: () => Navigator.of(context).push(
                MaterialPageRoute(
                  builder: (_) => OrdersListScreen(onUnauthorized: _onUnauthorized),
                ),
              ).then((_) => _loadOrderCount()),
              tooltip: 'Orders',
            ),
            IconButton(
              icon: const Icon(Icons.notifications_outlined),
              onPressed: () => Navigator.of(context).push(
                MaterialPageRoute(
                  builder: (_) => NotificationsScreen(onUnauthorized: _onUnauthorized),
                ),
              ),
              tooltip: 'Notifications',
            ),
          ],
        ],
      ),
      body: IndexedStack(
        index: _index,
        children: [
          HomeScreen(
            onUnauthorized: _onUnauthorized,
            refreshTrigger: _homeRefreshTrigger,
            orderCountRefreshTrigger: _orderCountRefreshTrigger,
          ),
          ServicesScreen(onUnauthorized: _onUnauthorized, onOrderCreated: _onOrderCreated),
          ShopScreen(onUnauthorized: _onUnauthorized, onOrderCreated: _onOrderCreated),
          SettingsScreen(onUnauthorized: _onUnauthorized),
        ],
      ),
      bottomNavigationBar: NavigationBar(
        selectedIndex: _index,
        onDestinationSelected: (i) {
          setState(() => _index = i);
          if (i == 0) _loadOrderCount();
        },
        destinations: const [
          NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
          NavigationDestination(icon: Icon(Icons.build), label: 'Services'),
          NavigationDestination(icon: Icon(Icons.shopping_cart), label: 'Shop'),
          NavigationDestination(icon: Icon(Icons.settings), label: 'Settings'),
        ],
      ),
    );
  }

  String get _title {
    switch (_index) {
      case 0: return 'Jambo';
      case 1: return 'Services';
      case 2: return 'Shop';
      case 3: return 'Settings';
      default: return 'Jambo';
    }
  }
}
