import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:permission_handler/permission_handler.dart';

import 'package:doormile/main.dart';
import 'package:doormile/core/theme/app_colors.dart';
import 'package:doormile/core/theme/app_theme.dart';
import 'package:doormile/features/dashboard/screens/home_screen.dart';
import 'package:doormile/features/tracking/screens/my_orders_screen.dart';
import 'package:doormile/features/dashboard/screens/summary_screen.dart';
import 'package:doormile/features/dashboard/screens/profile_screen.dart';

/// Root scaffold hosting the 5-tab bottom navigation.
class MainShell extends StatefulWidget {
  final int initialIndex;
  const MainShell({super.key, this.initialIndex = 0});

  @override
  State<MainShell> createState() => _MainShellState();
}

class _MainShellState extends State<MainShell> {
  late int _index = widget.initialIndex;

  @override
  void initState() {
    super.initState();
    _requestPermissions();
  }

  Future<void> _requestPermissions() async {
    if (kIsWeb) return;
    try {
      final status = await Permission.locationWhenInUse.status;
      if (!status.isGranted) {
        await Permission.locationWhenInUse.request();
      }
    } catch (e) {
      debugPrint('Location permission error: $e');
    }
  }

  // Tab indices: 0 Home, 1 Track, 3 Wallet, 4 Profile. 2 = Book (action).
  final _pages = const [
    HomeScreen(),
    MyOrdersScreen(embedded: true),
    SizedBox.shrink(), // Book slot — never shown (navigates away)
    SummaryScreen(),
    ProfileScreen(),
  ];

  void _onTap(int i) {
    if (i == 2) {
      Navigator.pushNamed(context, Routes.bookingPickup);
      return;
    }
    setState(() => _index = i);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.surface,
      body: IndexedStack(index: _index, children: _pages),
      extendBody: true,
      bottomNavigationBar: _BottomBar(index: _index, onTap: _onTap),
    );
  }
}

class _BottomBar extends StatelessWidget {
  final int index;
  final ValueChanged<int> onTap;
  const _BottomBar({required this.index, required this.onTap});

  static const _items = [
    (_NavItem(Icons.home_rounded, Icons.home_outlined, 'Home')),
    (_NavItem(Icons.map_rounded, Icons.map_outlined, 'Track')),
    (_NavItem(Icons.add_circle, Icons.add_circle, 'Book')),
    (_NavItem(Icons.bar_chart_rounded, Icons.bar_chart_outlined, 'Summary')),
    (_NavItem(Icons.person_rounded, Icons.person_outline, 'Profile')),
  ];

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: false,
      minimum: const EdgeInsets.fromLTRB(14, 0, 14, 12),
      child: Container(
        height: 72,
        decoration: BoxDecoration(
          color: AppColors.surfaceContainerLowest.withValues(alpha: 0.96),
          borderRadius: BorderRadius.circular(24),
          border: Border.all(color: Colors.white),
          boxShadow: AppTheme.cardShadow,
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(24),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: List.generate(_items.length, (i) {
              final item = _items[i];
              final active = i == index;
              if (i == 2) {
                // Centre "Book" action button.
                return _BookButton(onTap: () => onTap(2));
              }
              return Expanded(
                child: InkWell(
                  onTap: () => onTap(i),
                  borderRadius: BorderRadius.circular(18),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      AnimatedContainer(
                        duration: const Duration(milliseconds: 180),
                        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 5),
                        decoration: BoxDecoration(
                          color: active ? AppColors.primaryFixed : Colors.transparent,
                          borderRadius: BorderRadius.circular(999),
                        ),
                        child: Icon(active ? item.active : item.inactive,
                            color: active ? AppColors.primary : AppColors.onSurfaceVariant,
                            size: 22),
                      ),
                      const SizedBox(height: 2),
                      Text(item.label,
                          maxLines: 1,
                          style: AppTheme.caption.copyWith(
                            color: active ? AppColors.primary : AppColors.onSurfaceVariant,
                            fontWeight: active ? FontWeight.w700 : FontWeight.w500,
                          )),
                    ],
                  ),
                ),
              );
            }),
          ),
        ),
      ),
    );
  }
}

class _BookButton extends StatelessWidget {
  final VoidCallback onTap;
  const _BookButton({required this.onTap});

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(40),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 46,
              height: 46,
              decoration: BoxDecoration(
                gradient: const LinearGradient(
                  colors: [AppColors.primaryContainer, AppColors.primary],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                ),
                shape: BoxShape.circle,
                boxShadow: [
                  BoxShadow(
                    color: AppColors.primary.withValues(alpha: 0.28),
                    blurRadius: 16,
                    offset: const Offset(0, 8),
                  )
                ],
              ),
              child: const Icon(Icons.add, color: Colors.white, size: 28),
            ),
            const SizedBox(height: 2),
            Text('Book',
                style: AppTheme.caption.copyWith(
                    color: AppColors.primary, fontWeight: FontWeight.w700)),
          ],
        ),
      ),
    );
  }
}

class _NavItem {
  final IconData active;
  final IconData inactive;
  final String label;
  const _NavItem(this.active, this.inactive, this.label);
}
