import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'app.dart';
import 'screens/login_screen.dart';
import 'screens/update_screen.dart';
import 'services/auth_service.dart';
import 'package:in_app_update/in_app_update.dart';
import 'dart:io';
import 'theme/app_theme.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setSystemUIOverlayStyle(
    const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.dark,
    ),
  );

  AuthUser? initialUser;
  try {
    initialUser = await AuthService().getSavedUser();
  } catch (_) {}

  runApp(DoorMileApp(initialUser: initialUser));
}

class DoorMileApp extends StatelessWidget {
  final AuthUser? initialUser;
  
  const DoorMileApp({super.key, this.initialUser});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Doormile CRM',
      debugShowCheckedModeBanner: false,
      theme: buildAppTheme(),
      home: AuthGate(initialUser: initialUser),
      builder: (context, child) {
        final mediaQuery = MediaQuery.of(context);
        return Container(
          color: AppColors.scaffold,
          child: Center(
            child: ConstrainedBox(
              constraints: const BoxConstraints(maxWidth: 500),
              child: MediaQuery(
                data: mediaQuery.copyWith(
                  textScaler: mediaQuery.textScaler.clamp(
                    minScaleFactor: 0.85,
                    maxScaleFactor: 1.15,
                  ),
                ),
                child: child!,
              ),
            ),
          ),
        );
      },
    );
  }
}

class AuthGate extends StatefulWidget {
  final AuthUser? initialUser;

  const AuthGate({super.key, this.initialUser});

  @override
  State<AuthGate> createState() => _AuthGateState();
}

class _AuthGateState extends State<AuthGate> {
  AuthUser? _user;
  bool _updateRequired = false;

  @override
  void initState() {
    super.initState();
    _user = widget.initialUser;
    _checkForUpdates();
  }

  Future<void> _checkForUpdates() async {
    try {
      if (Platform.isAndroid) {
        final info = await InAppUpdate.checkForUpdate();
        if (info.updateAvailability == UpdateAvailability.updateAvailable) {
          setState(() => _updateRequired = true);
          await InAppUpdate.performImmediateUpdate();
        }
      }
    } catch (e) {
      // Ignored: Not a supported Android device or Play Store not accessible
    }
  }

  Future<void> _login(AuthUser user) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('auth_user_data', jsonEncode(user.toJson()));
      await prefs.setString('user_name', user.name);
    } catch (_) {}
    setState(() => _user = user);
  }

  Future<void> _logout() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove('auth_user_data');
      await prefs.remove('user_name');
    } catch (_) {}
    setState(() => _user = null);
  }

  @override
  Widget build(BuildContext context) {
    if (_updateRequired) {
      return const UpdateRequiredScreen();
    }
    if (_user == null) {
      return LoginScreen(
        onLoggedIn: _login,
      );
    }
    return AppShell(currentUser: _user!, onLogout: _logout);
  }
}
