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

import 'home/home_screen.dart';
import 'channel_list/channel_list_screen.dart';
import 'screens/login_screen.dart';
import 'services/auth_service.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Permission.microphone.request();
  runApp(const WalkieTalkieApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'WalkieTalkie',
      theme: ThemeData(
        brightness: Brightness.dark,
        colorScheme: ColorScheme.dark(
          primary: const Color(0xFF00C853),
          secondary: const Color(0xFF1DE9B6),
          surface: const Color(0xFF1C1C1E),
        ),
        scaffoldBackgroundColor: Colors.black,
        useMaterial3: true,
      ),
      // استفاده از onGenerateRoute برای مدیریت مسیرها
      onGenerateRoute: (settings) {
        switch (settings.name) {
          case '/':
            return MaterialPageRoute(builder: (_) => const _Splash());
          case '/home':
            return MaterialPageRoute(builder: (_) => const HomeScreen());
          case '/channel_list':
            return MaterialPageRoute(builder: (_) => const ChannelListScreen());
          case '/login':
            return MaterialPageRoute(builder: (_) => const LoginScreen());
          default:
            return MaterialPageRoute(builder: (_) => const _Splash());
        }
      },
      // صفحه پیش‌فرض برنامه (اسپلش)
      initialRoute: '/',
    );
  }
}

class _Splash extends StatefulWidget {
  const _Splash();

  @override
  State<_Splash> createState() => _SplashState();
}

class _SplashState extends State<_Splash> {
  bool _loading = false;

  // متغیرهای مربوط به باتری
  static const _nativeChannel = MethodChannel('com.example.watch/launcher');
  int _batteryLevel = 0;
  bool _isCharging = false;

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

  Future<void> _loadBattery() async {
    try {
      final info = await _nativeChannel.invokeMapMethod<String, dynamic>(
        'getBatteryInfo',
      );
      if (!mounted || info == null) return;
      setState(() {
        _batteryLevel = (info['level'] as int?) ?? 0;
        _isCharging = (info['isCharging'] as bool?) ?? false;
      });
    } catch (_) {}
  }

  Future<void> _onTap() async {
    if (_loading) return;
    setState(() => _loading = true);

    final loggedIn = await AuthService().isLoggedIn();

    if (!mounted) return;

    // هدایت کاربر بر اساس وضعیت لاگین
    Navigator.pushReplacementNamed(context, loggedIn ? '/home' : '/login');
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _onTap,
      child: Scaffold(
        backgroundColor: Colors.black,
        body: Center(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  width: 64,
                  height: 64,
                  decoration: const BoxDecoration(
                    color: Colors.white,
                    shape: BoxShape.circle,
                  ),
                  padding: const EdgeInsets.all(1),
                  child: Image.asset(
                    'assets/images/logo.png',
                    fit: BoxFit.contain,
                  ),
                ),
                const SizedBox(height: 14),
                const Text(
                  'مرکز هوش مصنوعی',
                  style: TextStyle(
                    color: Colors.green,
                    fontSize: 15,
                    fontWeight: FontWeight.bold,
                    letterSpacing: 0.4,
                  ),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 3),
                const Text(
                  'و فناوری‌های نو ظهور',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14,
                    letterSpacing: 0.3,
                  ),
                  textAlign: TextAlign.center,
                ),
                const Text(
                  'سپاه ثارلله استان کرمان',
                  style: TextStyle(
                    color: Colors.red,
                    fontSize: 14,
                    letterSpacing: 0.3,
                  ),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 16),
                if (_loading)
                  const SizedBox(
                    width: 16,
                    height: 16,
                    child: CircularProgressIndicator(
                      color: Color(0xFF00C853),
                      strokeWidth: 2,
                    ),
                  )
                else
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        _isCharging ? Icons.bolt : Icons.battery_std,
                        color: _isCharging
                            ? const Color(0xFF00C853)
                            : (_batteryLevel <= 15
                                  ? const Color(0xFFFF1744)
                                  : Colors.white24),
                        size: 10,
                      ),
                      const SizedBox(width: 4),
                      Text(
                        '$_batteryLevel%',
                        style: TextStyle(
                          color: _isCharging
                              ? const Color(0xFF00C853)
                              : (_batteryLevel <= 15
                                    ? const Color(0xFFFF1744)
                                    : Colors.white24),
                          fontSize: 9,
                        ),
                      ),
                    ],
                  ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
