import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'package:google_maps_flutter_android/google_maps_flutter_android.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'api_client.dart';
import 'auth_storage.dart';
import 'screens/login_screen.dart';
import 'screens/register_screen.dart';
import 'screens/main_shell_screen.dart';
import 'screens/update_required_screen.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // Ensure Google Maps Android platform view is registered before any map is shown
  // (fixes "platform view of unregistered type: plugins.flutter.dev/google_maps_android").
  final platform = GoogleMapsFlutterPlatform.instance;
  if (platform is GoogleMapsFlutterAndroid) {
    platform.useAndroidViewSurface = true;
  }
  await MobileAds.instance.initialize();
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  SystemChrome.setSystemUIOverlayStyle(
    const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.light,
    ),
  );
  runApp(const FueloApp());
}

// ── Theme ─────────────────────────────────────────────────────────────────────

ThemeData _buildTheme() {
  const amber = Color(0xFFFF9500);
  const bg = Color(0xFF0F1114);

  return ThemeData(
    useMaterial3: true,
    brightness: Brightness.dark,
    scaffoldBackgroundColor: bg,
    colorScheme: const ColorScheme.dark(
      primary: amber,
      onPrimary: Colors.black,
      secondary: amber,
      onSecondary: Colors.black,
      surface: Color(0xFF1A1D22),
      onSurface: Color(0xFFF2F2F2),
      error: Color(0xFFFF4545),
    ),
    fontFamily: 'RobotoMono',
    appBarTheme: const AppBarTheme(
      backgroundColor: Color(0xFF1A1D22),
      foregroundColor: Color(0xFFF2F2F2),
      elevation: 0,
      scrolledUnderElevation: 0,
      systemOverlayStyle: SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: Brightness.light,
      ),
    ),
    filledButtonTheme: FilledButtonThemeData(
      style: FilledButton.styleFrom(
        backgroundColor: amber,
        foregroundColor: Colors.black,
        textStyle: const TextStyle(
          fontWeight: FontWeight.w800,
          letterSpacing: 2,
          fontSize: 14,
        ),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(12)),
        ),
        minimumSize: const Size.fromHeight(54),
      ),
    ),
    elevatedButtonTheme: ElevatedButtonThemeData(
      style: ElevatedButton.styleFrom(
        backgroundColor: amber,
        foregroundColor: Colors.black,
        elevation: 0,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(12)),
        ),
        minimumSize: const Size.fromHeight(54),
      ),
    ),
    cardTheme: CardThemeData(
      color: const Color(0xFF21252D),
      elevation: 0,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.all(Radius.circular(16)),
        side: const BorderSide(color: Color(0xFF2C3040), width: 1),
      ),
    ),
    dividerTheme: const DividerThemeData(
      color: Color(0xFF2C3040),
      space: 1,
      thickness: 1,
    ),
    inputDecorationTheme: InputDecorationTheme(
      filled: true,
      fillColor: const Color(0xFF21252D),
      border: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(12)),
        borderSide: const BorderSide(color: Color(0xFF2C3040), width: 1.5),
      ),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(12)),
        borderSide: const BorderSide(color: Color(0xFF2C3040), width: 1.5),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(12)),
        borderSide: const BorderSide(color: amber, width: 1.5),
      ),
      hintStyle: const TextStyle(color: Color(0xFF8A8F99)),
      labelStyle: const TextStyle(color: Color(0xFF8A8F99)),
    ),
    textTheme: const TextTheme(
      headlineLarge: TextStyle(
        color: Color(0xFFF2F2F2),
        fontWeight: FontWeight.w700,
        fontSize: 32,
      ),
      headlineMedium: TextStyle(
        color: Color(0xFFF2F2F2),
        fontWeight: FontWeight.w700,
        fontSize: 28,
      ),
      headlineSmall: TextStyle(
        color: Color(0xFFF2F2F2),
        fontWeight: FontWeight.w700,
        fontSize: 24,
      ),
      titleLarge: TextStyle(
        color: Color(0xFFF2F2F2),
        fontWeight: FontWeight.w600,
        fontSize: 18,
      ),
      titleMedium: TextStyle(
        color: Color(0xFFF2F2F2),
        fontWeight: FontWeight.w600,
        fontSize: 15,
      ),
      titleSmall: TextStyle(
        color: Color(0xFF8A8F99),
        fontWeight: FontWeight.w500,
        fontSize: 13,
      ),
      bodyLarge: TextStyle(color: Color(0xFFF2F2F2), fontSize: 15, height: 1.5),
      bodyMedium: TextStyle(
        color: Color(0xFFF2F2F2),
        fontSize: 13,
        height: 1.5,
      ),
      bodySmall: TextStyle(color: Color(0xFF8A8F99), fontSize: 12, height: 1.5),
    ),
  );
}

// ── App ───────────────────────────────────────────────────────────────────────

class FueloApp extends StatelessWidget {
  const FueloApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Jambo',
      debugShowCheckedModeBanner: false,
      theme: _buildTheme(),
      initialRoute: '/splash',
      routes: {
        '/splash': (context) => const _SplashScreen(),
        '/login': (context) => const LoginScreen(),
        '/register': (context) => const RegisterScreen(),
        '/dashboard': (context) => const MainShellScreen(),
        '/update-required': (context) {
          final args =
              ModalRoute.of(context)!.settings.arguments
                  as UpdateRequiredPayload?;
          return UpdateRequiredScreen(
            payload: args ?? UpdateRequiredPayload(storeUrls: {}),
          );
        },
      },
    );
  }
}

// ── Splash screen ─────────────────────────────────────────────────────────────

class _SplashScreen extends StatefulWidget {
  const _SplashScreen();

  @override
  State<_SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<_SplashScreen>
    with SingleTickerProviderStateMixin {
  late final AnimationController _ctrl;
  late final Animation<double> _scaleAnim;
  late final Animation<double> _fadeAnim;

  @override
  void initState() {
    super.initState();
    _ctrl = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 800),
    );
    _scaleAnim = Tween<double>(
      begin: 0.7,
      end: 1.0,
    ).animate(CurvedAnimation(parent: _ctrl, curve: Curves.easeOutBack));
    _fadeAnim = CurvedAnimation(parent: _ctrl, curve: Curves.easeOut);
    _ctrl.forward();
    _runStartup();
  }

  @override
  void dispose() {
    _ctrl.dispose();
    super.dispose();
  }

  /// Returns true if current >= min (semantic version comparison).
  bool _isVersionAtLeast(String current, String min) {
    List<int> parse(String v) {
      return v.split('.').map((s) => int.tryParse(s.trim()) ?? 0).toList();
    }

    final c = parse(current);
    final m = parse(min);
    for (var i = 0; i < c.length || i < m.length; i++) {
      final cv = i < c.length ? c[i] : 0;
      final mv = i < m.length ? m[i] : 0;
      if (cv > mv) return true;
      if (cv < mv) return false;
    }
    return true;
  }

  Future<void> _runStartup() async {
    await Future.delayed(const Duration(milliseconds: 1600));
    if (!mounted) return;

    final dio = createApiClient(() {});
    try {
      final response = await dio.get<Map<String, dynamic>>('/api/version');
      final data = response.data?['data'] as Map<String, dynamic>?;
      final minVersion = data?['min_version'] as String?;
      final storeUrlsJson = data?['store_urls'] as Map<String, dynamic>?;

      if (minVersion == null ||
          minVersion.trim().isEmpty ||
          storeUrlsJson == null) {
        _checkAuth();
        return;
      }

      final packageInfo = await PackageInfo.fromPlatform();
      final currentVersion = packageInfo.version;

      if (!_isVersionAtLeast(currentVersion, minVersion.trim())) {
        final payload = UpdateRequiredPayload.fromJson(
          storeUrlsJson,
          onRetry: () {
            if (!mounted) return;
            Navigator.of(context).pop();
            _runStartup();
          },
        );
        if (!mounted) return;
        await Navigator.of(
          context,
        ).pushNamed<void>('/update-required', arguments: payload);
        return;
      }
    } catch (_) {
      // Network or parse error: proceed so app is not stuck
    }
    if (!mounted) return;
    _checkAuth();
  }

  Future<void> _checkAuth() async {
    final token = await AuthStorage.getToken();
    if (token != null && token.isNotEmpty) {
      Navigator.of(context).pushNamedAndRemoveUntil('/dashboard', (r) => false);
    } else {
      Navigator.of(context).pushReplacementNamed('/login');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF0F1114),
      body: Center(
        child: FadeTransition(
          opacity: _fadeAnim,
          child: ScaleTransition(
            scale: _scaleAnim,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // Icon badge
                Container(
                  width: 88,
                  height: 88,
                  decoration: BoxDecoration(
                    color: const Color(0x33FF9500),
                    borderRadius: BorderRadius.circular(24),
                    border: Border.all(
                      color: const Color(0xFFFF9500).withOpacity(0.4),
                      width: 2,
                    ),
                    boxShadow: [
                      BoxShadow(
                        color: const Color(0xFFFF9500).withOpacity(0.25),
                        blurRadius: 40,
                        spreadRadius: 4,
                      ),
                    ],
                  ),
                  child: const Icon(
                    Icons.water_drop_rounded,
                    color: Color(0xFFFF9500),
                    size: 44,
                  ),
                ),

                const SizedBox(height: 28),

                // Wordmark
                const Text(
                  'JAMBO',
                  style: TextStyle(
                    fontFamily: 'RobotoMono',
                    color: Color(0xFFF2F2F2),
                    fontSize: 36,
                    fontWeight: FontWeight.w700,
                    letterSpacing: 8,
                  ),
                ),

                const SizedBox(height: 6),

                // Tagline
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      width: 20,
                      height: 2,
                      color: const Color(0xFFFF9500),
                    ),
                    const SizedBox(width: 8),
                    const Text(
                      'GAS & FUEL DELIVERY',
                      style: TextStyle(
                        color: Color(0xFF8A8F99),
                        fontSize: 11,
                        letterSpacing: 3,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    const SizedBox(width: 8),
                    Container(
                      width: 20,
                      height: 2,
                      color: const Color(0xFFFF9500),
                    ),
                  ],
                ),

                const SizedBox(height: 56),

                // Loading indicator
                const SizedBox(
                  width: 24,
                  height: 24,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(
                      Color(0xFFFF9500),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
