import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:doormile/shared/state/app_state.dart';
import 'package:doormile/core/theme/app_theme.dart';
import 'package:doormile/core/theme/app_colors.dart';
import 'package:doormile/features/auth/screens/onboarding_screen.dart';
import 'package:doormile/features/auth/screens/login_screen.dart';
import 'package:doormile/features/auth/screens/signup_screen.dart';
import 'package:doormile/features/auth/screens/otp_screen.dart';
import 'package:doormile/features/auth/screens/pin_screen.dart';
import 'package:doormile/features/dashboard/screens/main_shell.dart';
import 'package:doormile/features/booking/screens/booking_pickup_screen.dart';
import 'package:doormile/features/booking/screens/parcel_details_screen.dart';
import 'package:doormile/features/booking/screens/service_price_screen.dart';
import 'package:doormile/features/booking/screens/booking_preview_screen.dart';
import 'package:doormile/features/booking/screens/booking_success_screen.dart';
import 'package:doormile/features/tracking/screens/my_orders_screen.dart';
import 'package:doormile/features/tracking/screens/live_tracking_screen.dart';
import 'package:doormile/features/tracking/screens/shipment_journey_screen.dart';
import 'package:doormile/features/support/screens/help_support_screen.dart';
import 'package:doormile/features/dashboard/screens/saved_addresses_screen.dart';
import 'package:doormile/features/support/screens/chat_screen.dart';
import 'package:doormile/shared/models/models.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  try {
    await Firebase.initializeApp();
  } catch (e) {
    debugPrint('Firebase initialization error: $e');
  }

  final prefs = await SharedPreferences.getInstance();
  final token = prefs.getString('auth_token');
  final initialRoute = (token != null && token.isNotEmpty) ? Routes.home : Routes.onboarding;

  SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
    statusBarColor: Colors.transparent,
    statusBarIconBrightness: Brightness.dark,
  ));
  runApp(DoormileApp(initialRoute: initialRoute));
}

class Routes {
  static const splash = '/';
  static const onboarding = '/onboarding';
  static const login = '/login';
  static const signup = '/signup';
  static const otp = '/otp';
  static const enterPin = '/enter-pin';
  static const setPin = '/set-pin';
  static const resetPin = '/reset-pin';
  static const home = '/home';
  static const bookingPickup = '/booking/pickup';
  static const parcelDetails = '/booking/details';
  static const servicePrice = '/booking/service';
  static const bookingPreview = '/booking/preview';
  static const bookingSuccess = '/booking/success';
  static const myOrders = '/orders';
  static const liveTracking = '/tracking/live';
  static const shipmentJourney = '/tracking/journey';
  static const help = '/help';
  static const addresses = '/addresses';
  static const chat = '/chat';
}

class DoormileApp extends StatelessWidget {
  final String initialRoute;
  const DoormileApp({super.key, required this.initialRoute});

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => AppState(),
      child: _buildApp(),
    );
  }

  Widget _buildApp() {
    return MaterialApp(
      title: 'Doormile',
      debugShowCheckedModeBanner: false,
      theme: AppTheme.light,
      initialRoute: initialRoute,
      onGenerateRoute: (settings) {
        Widget page;
        switch (settings.name) {
          case Routes.onboarding:
            page = const OnboardingScreen();
            break;
          case Routes.login:
            page = const LoginScreen();
            break;
          case Routes.signup:
            page = const SignupScreen();
            break;
          case Routes.otp:
            page = const OtpScreen();
            break;
          case Routes.enterPin:
            page = const PinScreen(mode: PinMode.enter);
            break;
          case Routes.setPin:
            page = const PinScreen(mode: PinMode.set);
            break;
          case Routes.resetPin:
            page = const PinScreen(mode: PinMode.reset);
            break;
          case Routes.home:
            page = const MainShell();
            break;
          case Routes.bookingPickup:
            page = const BookingPickupScreen();
            break;
          case Routes.parcelDetails:
            page = const ParcelDetailsScreen();
            break;
          case Routes.servicePrice:
            page = const ServicePriceScreen();
            break;
          case Routes.bookingPreview:
            page = const BookingPreviewScreen();
            break;
          case Routes.bookingSuccess:
            page = const BookingSuccessScreen();
            break;
          case Routes.myOrders:
            page = const MyOrdersScreen();
            break;
          case Routes.liveTracking:
            page = LiveTrackingScreen(order: settings.arguments as Order?);
            break;
          case Routes.shipmentJourney:
            page = ShipmentJourneyScreen(order: settings.arguments as Order?);
            break;
          case Routes.help:
            page = const HelpSupportScreen();
            break;
          case Routes.addresses:
            page = const SavedAddressesScreen();
            break;
          case Routes.chat:
            final chatArgs = settings.arguments as Map<String, String?>? ?? {};
            page = Builder(
              builder: (context) {
                final appState = Provider.of<AppState>(context, listen: false);
                return ChatScreen(
                  riderName: chatArgs['milerName'] ?? 'Rider',
                  bookingId: chatArgs['bookingId'] ?? '',
                  authToken: appState.authToken,
                );
              },
            );
            break;
          default:
            page = const MainShell();
        }
        return PageRouteBuilder(
          settings: settings,
          pageBuilder: (_, __, ___) => page,
          transitionsBuilder: (_, animation, __, child) {
            return FadeTransition(
              opacity: animation,
              child: SlideTransition(
                position: Tween(begin: const Offset(0, 0.02), end: Offset.zero)
                    .animate(CurvedAnimation(parent: animation, curve: Curves.easeOut)),
                child: child,
              ),
            );
          },
          transitionDuration: const Duration(milliseconds: 280),
        );
      },
    );
  }
}

/// Selection colour helper used by text fields.
final selectionTheme = const TextSelectionThemeData(
  selectionColor: AppColors.primaryFixed,
  cursorColor: AppColors.primary,
);
