import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:page_transition/page_transition.dart';

import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

import 'package:fl_sevengen_society_user_app/localization/localization.dart';
import 'package:fl_sevengen_society_user_app/localization/localization_const.dart';
import 'package:fl_sevengen_society_user_app/theme/theme.dart';
import 'package:fl_sevengen_society_user_app/screens/screens.dart';

// If screens.dart doesn't export LeadFormScreen, import it explicitly:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  try {
    // Only initialize if no Dart-side Firebase apps exist.
    if (Firebase.apps.isEmpty) {
      await Firebase.initializeApp(
        options: DefaultFirebaseOptions.currentPlatform,
      );
    }
  } on FirebaseException catch (e) {
    if (e.code == 'duplicate-app' || e.message?.contains('duplicate-app') == true) {
      // Already initialized by native side - ignore
    } else {
      rethrow;
    }
  } catch (e) {
    final errStr = e.toString();
    if (errStr.contains('duplicate-app')) {
      // ignore
    } else {
      rethrow;
    }
  }

  runApp(const MyApp());
}

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

  static void setLocale(BuildContext context, Locale locale) {
    _MyAppState state = context.findAncestorStateOfType<_MyAppState>()!;
    state.setLocale(locale);
  }

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Locale? _locale;

  void setLocale(locale) {
    setState(() {
      _locale = locale;
    });
  }

  @override
  void didChangeDependencies() {
    getLocale().then((locale) {
      setState(() {
        _locale = locale;
      });
    });
    getIntLanguageValue();
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: Brightness.dark,
      ),
    );

    return MaterialApp(
      title: 'Rotary United',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: primaryColor,
          primary: primaryColor,
        ),
        primaryColor: primaryColor,
        scaffoldBackgroundColor: whiteColor,
        fontFamily: 'Inter',
        appBarTheme: const AppBarTheme(
          surfaceTintColor: Colors.transparent,
        ),
      ),
      home: const SplashScreen(),
      onGenerateRoute: routes,
      locale: _locale,
      supportedLocales: const [
        Locale('en'),
        Locale('ta'),
        Locale('hi'),
        Locale('id'),
        Locale('zh'),
        Locale('ar'),
      ],
      localizationsDelegates: [
        DemoLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      localeResolutionCallback: (deviceLocale, supportedLocales) {
        for (var locale in supportedLocales) {
          if (locale.languageCode == deviceLocale?.languageCode) {
            return deviceLocale;
          }
        }
        return supportedLocales.first;
      },
    );
  }

  // ===================== ROUTES =====================
  Route<dynamic>? routes(RouteSettings settings) {
    switch (settings.name) {
      case '/':
        return PageTransition(
          child: const SplashScreen(),
          type: PageTransitionType.fade,
          settings: settings,
        );

      case '/onboarding':
        return PageTransition(
          child: const OnboardingScreen(),
          type: PageTransitionType.fade,
          settings: settings,
        );

      case '/login':
        return PageTransition(
          child: const LoginScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/register':
        return PageTransition(
          child: const RegisterScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/referrals':
        return PageTransition(
          child: const ReferralsScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

        case '/addReferral':
        return PageTransition(
          child: const AddReferralScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );
    // FIXED OTP ROUTE
      case '/otp':
        {
          final args = settings.arguments;
          if (args is Map<String, dynamic> &&
              args.containsKey('verificationId') &&
              args.containsKey('phoneNumber')) {
            final verificationId = args['verificationId'] as String;
            final phoneNumber = args['phoneNumber'] as String;
            final onVerified = args['onVerified'] as VoidCallback?;
            return PageTransition(
              child: OTPScreen(
                verificationId: verificationId,
                phoneNumber: phoneNumber,
                onVerified: onVerified,
              ),
              type: PageTransitionType.rightToLeft,
              settings: settings,
            );
          } else {
            return PageTransition(
              child: const LoginScreen(),
              type: PageTransitionType.rightToLeft,
              settings: settings,
            );
          }
        }

      case '/bottomBar':
        return PageTransition(
          child: const BottomBar(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/home':
        return PageTransition(
          child: const HomeScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/teams':
        return PageTransition(
          child: const TeamsScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );
    // ... existing routes retained (members, call, message, etc.)
      case '/members':
        return PageTransition(
          child: const MembersScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/call':
        return PageTransition(
          child: const CallScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/message':
        return PageTransition(
          child: const MessageScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/visitors':
        return PageTransition(
          child: const VisitorsScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

        case '/events':
        return PageTransition(
          child: const EventDisplay(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );



      case '/preApproveVisitors':
        return PageTransition(
          child: const PreApproveVisitorsScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/noticeBoard':
        return PageTransition(
          child: const NoticeBoardScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/payment':
        return PageTransition(
          child: const PaymentScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/success':
        return PageTransition(
          child: const SuccessScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/paymentMethods':
        return PageTransition(
          child: const PaymemtMethodScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/bookAmenities':
        return PageTransition(
          child: const BookedAmenitiesScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/selectAmenities':
        return PageTransition(
          child: const SelectAmenitiesScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/bookAmenitiesProceed':
        return PageTransition(
          child: const BookAmenitiesProceedScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/helpDesk':
        return PageTransition(
          child: const HelpDeskScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/complaintDetail':
        return PageTransition(
          child: const ComplaintDetailScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/addComplaint':
        return PageTransition(
          child: const AddComplaintScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/notification':
        return PageTransition(
          child: const NotificationScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/calling':
        return PageTransition(
          child: const CallingScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/chats':
        return PageTransition(
          child: const ChatsScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/search':
        return PageTransition(
          child: const SearchScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/service':
        return PageTransition(
          child: const ServiceScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/profile':
        return PageTransition(
          child: const ProfileScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/settings':
        return PageTransition(
          child: const SettingsScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/editProfile':
        return PageTransition(
          child: const EditProfileScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/language':
        return PageTransition(
          child: const LanguageScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/getSupport':
        return PageTransition(
          child: const GetSupportScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/termsAndCondition':
        return PageTransition(
          child: const TermsAndConditionScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/privacyPolicy':
        return PageTransition(
          child: const PrivacyPolicyScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

    // --------- NEW service routes ----------
      case '/lead':
        return PageTransition(
          child: const LeadFormScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );
      case '/leaddisplay':
        return PageTransition(
          child: const LeadDisplayScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/feedback-app':
        return PageTransition(
          child: const FeedbackAppScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/specific-ask':
        return PageTransition(
          child: const SpecificAskScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/viewreplayask':
        final args = settings.arguments as Map<String, dynamic>;

        return PageTransition(
          child: AskViewReplyScreen(
            phone: args['phone'].toString(),
          ),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );


      case '/chat':
        return PageTransition(
          child: const ChatsScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/announcements':
        return PageTransition(
          child: const AnnouncementsScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/notifications':
        return PageTransition(
          child: const NotificationScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/AboutRmbf':
        return PageTransition(
          child: const AboutRMBFScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );
      case '/referral-to-referral':
        return PageTransition(
          child: const ReferralToReferralScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );
      case '/SpecificAskForm':
        return PageTransition(
          child: const AskFormScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/SpecificAskList':
        return PageTransition(
          child: const AskListScreen(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

      case '/SpecificAskReply':
        final args = settings.arguments as Map<String, dynamic>;

        return PageTransition(
          child: AskReplyScreen(
            id: args['id'].toString(),
            name: args['name'].toString(),
            phone: args['phone'].toString(),
            details: args['details'].toString(),
          ),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );

        case '/celebrationtoday':
        return PageTransition(
          child: const CelebrationToday(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );
      case '/openvertical':
        return PageTransition(
          child: const OpenVertical(),
          type: PageTransitionType.rightToLeft,
          settings: settings,
        );
      default:
        return null;
    }
  }
}
