import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:generp/Utils/commonWidgets.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

import '../Notifiers/splashVersionNotifier.dart';
import '../Utils/commonServices.dart';

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

  @override
  State<Splash> createState() => _SplashState();
}
// class _SplashState extends State<Splash> {
//   late Image splashImage;
//   Map _source = {ConnectivityResult.none: false};
//   final MyConnectivity _connectivity = MyConnectivity.instance;
//
//   @override
//   void initState() {
//     super.initState();
//     _connectivity.initialise();
//     _connectivity.myStream.listen((source) {
//       setState(() {
//         _source = source;
//         String newConnection;
//         switch (_source.keys.toList()[0]) {
//           case ConnectivityResult.mobile:
//           case ConnectivityResult.wifi:
//             newConnection = 'Online';
//             break;
//           case ConnectivityResult.none:
//           default:
//             newConnection = 'Offline';
//         }
//
//         // Reload the page when transitioning from Offline to Online
//         if (connection == 'Offline' && newConnection == 'Online') {
//           _reloadPage();
//         }
//         connection = newConnection;
//       });
//     });
//
//     splashImage = Image.asset("assets/images/ic_splash.jpg");
//     WidgetsBinding.instance.addPostFrameCallback((_) {
//       requestPermissions();
//       final splashProvider = Provider.of<SplashVersionNotifier>(
//         context,
//         listen: false,
//       );
//       splashProvider.initPackageInfo();
//       splashProvider.handleVersionCheck(context);
//     });
//   }
//
//   // Method to reload the page
//   void _reloadPage() {
//     // Reset any necessary state or re-run initialization logic
//     final splashProvider = Provider.of<SplashVersionNotifier>(
//       context,
//       listen: false,
//     );
//     splashProvider.initPackageInfo();
//     splashProvider.handleVersionCheck(context);
//   }
//
//   @override
//   void dispose() {
//     super.dispose();
//     _connectivity.disposeStream();
//   }
//
//   void requestPermissions() async {
//     await getCameraPermissions();
//     await getStoragePermission();
//     await getLocationPermissions();
//   }
//
//   Future<void> getStoragePermission() async {
//     if (await Permission.manageExternalStorage.request().isGranted) {
//       print("Storage");
//       setState(() {});
//     } else if (await Permission.storage.request().isPermanentlyDenied) {
//       print("Storage");
//       await openAppSettings();
//     } else if (await Permission.storage.request().isDenied) {
//       print("Storage");
//       setState(() {});
//     }
//   }
//
//   Future<void> getCameraPermissions() async {
//     if (await Permission.camera.request().isGranted) {
//       print("Camera1");
//       setState(() {});
//     } else if (await Permission.camera.request().isPermanentlyDenied) {
//       print("Camera2");
//       if (Platform.isAndroid) {
//         await openAppSettings();
//       } else if (Platform.isIOS) {
//         setState(() {});
//       }
//     } else if (await Permission.camera.request().isDenied) {
//       print("Camera3");
//       setState(() {});
//     }
//   }
//
//   Future<void> getLocationPermissions() async {
//     if (await Permission.location.request().isGranted) {
//       print("Location1a");
//       setState(() {});
//     } else if (await Permission.location.request().isPermanentlyDenied) {
//       print("Location1b");
//       if (Platform.isAndroid) {
//         await openAppSettings();
//       } else if (Platform.isIOS) {
//         // await AppSettings.openAppSettings(type: AppSettingsType.location);
//       }
//     } else if (await Permission.location.request().isDenied) {
//       print("Location1c");
//       setState(() {});
//     }
//
//     if (await Permission.locationAlways.request().isGranted) {
//       print("Location2a");
//       setState(() {});
//     } else if (await Permission.locationAlways.request().isPermanentlyDenied) {
//       print("Location2b");
//       if (Platform.isAndroid) {
//         await openAppSettings();
//       } else if (Platform.isIOS) {
//         // await AppSettings.openAppSettings(type: AppSettingsType.location);
//       }
//     } else if (await Permission.locationAlways.request().isDenied) {
//       print("Location2c");
//       setState(() {});
//     }
//
//     if (await Permission.locationWhenInUse.request().isGranted) {
//       print("Location3a");
//       setState(() {});
//     } else if (await Permission.locationWhenInUse.request().isPermanentlyDenied) {
//       print("Location3b");
//       if (Platform.isAndroid) {
//         await openAppSettings();
//       } else if (Platform.isIOS) {
//         // await AppSettings.openAppSettings(type: AppSettingsType.location);
//       }
//     } else if (await Permission.locationWhenInUse.request().isDenied) {
//       print("Location3c");
//       setState(() {});
//     }
//   }
//
//   Future<void> getNotificationsPermissions() async {
//     if (await Permission.notification.request().isGranted) {
//       setState(() {});
//     } else if (await Permission.notification.request().isPermanentlyDenied) {
//       await openAppSettings();
//     } else if (await Permission.notification.request().isDenied) {
//       setState(() {});
//     }
//   }
//
//   @override
//   void didChangeDependencies() {
//     super.didChangeDependencies();
//     precacheImage(splashImage.image, context);
//   }
//
//   @override
//   Widget build(BuildContext context) {
//     return (connection == 'Online')
//         ? SafeArea(
//       top: false,
//       bottom: Platform.isIOS ? false : true,
//       child: Scaffold(
//         resizeToAvoidBottomInset: true,
//         body: Consumer<SplashVersionNotifier>(
//           builder: (context, value, child) {
//             return Container(
//               alignment: Alignment.center,
//               child: Container(
//                 alignment: Alignment.center,
//                 height: 300,
//                 width: 300,
//                 child: splashImage,
//               ),
//             );
//           },
//         ),
//       ),
//     )
//         : NoNetwork(context);
//   }
// }

class _SplashState extends State<Splash> {
  late Image splashImage;
  Map _source = {ConnectivityResult.mobile: true};
  final MyConnectivity _connectivity = MyConnectivity.instance;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _connectivity.initialise();
    _connectivity.myStream.listen((source) {
      setState(() => _source = source);
    });
    splashImage = Image.asset("assets/images/ic_splash.jpg");
    WidgetsBinding.instance.addPostFrameCallback((_) {
      requestPermissions();
      final spalshProvider = Provider.of<SplashVersionNotifier>(
        context,
        listen: false,
      );
      spalshProvider.initPackageInfo();
      // spalshProvider.handleVersionCheck(context);
      if (connection == 'Online') {
        print("camer here");
        spalshProvider.handleVersionCheck(context);
      } else {
        spalshProvider.handleVersionCheck(context);
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _connectivity.disposeStream();
  }

  void requestPermissions() async {
    await getCameraPermissions();
    await getStoragePermission();
    await getLocationPermissions();
  }

  Future<void> getStoragePermission() async {
    if (await Permission.manageExternalStorage.request().isGranted) {
      print("Storage");
      setState(() {});
    } else if (await Permission.storage.request().isPermanentlyDenied) {
      print("Storage");
      await openAppSettings();
    } else if (await Permission.storage.request().isDenied) {
      print("Storage");
      setState(() {});
    }
  }

  Future<void> getCameraPermissions() async {
    if (await Permission.camera.request().isGranted) {
      print("Camera1");
      setState(() {});
    } else if (await Permission.camera.request().isPermanentlyDenied) {
      print("Camera2");
      if (Platform.isAndroid) {
        await openAppSettings();
      } else if (Platform.isIOS) {
        setState(() {});
      }
    } else if (await Permission.camera.request().isDenied) {
      print("Camera3");
      setState(() {});
    }
  }

  Future<void> getLocationPermissions() async {
    if (await Permission.location.request().isGranted) {
      print("Location1a");
      setState(() {});
    } else if (await Permission.location.request().isPermanentlyDenied) {
      print("Location1b");
      if (Platform.isAndroid) {
        await openAppSettings();
      } else if (Platform.isIOS) {
        // await AppSettings.openAppSettings(type: AppSettingsType.location);
      }
    } else if (await Permission.location.request().isDenied) {
      print("Location1c");
      setState(() {});
    }

    if (await Permission.locationAlways.request().isGranted) {
      print("Location2a");
      setState(() {});
    } else if (await Permission.locationAlways.request().isPermanentlyDenied) {
      print("Location2b");
      if (Platform.isAndroid) {
        await openAppSettings();
      } else if (Platform.isIOS) {
        // await AppSettings.openAppSettings(type: AppSettingsType.location);
      }
    } else if (await Permission.locationAlways.request().isDenied) {
      print("Location2c");
      setState(() {});
    }

    if (await Permission.locationWhenInUse.request().isGranted) {
      print("Location3a");
      setState(() {});
    } else if (await Permission.locationWhenInUse
        .request()
        .isPermanentlyDenied) {
      print("Location3b");
      if (Platform.isAndroid) {
        await openAppSettings();
      } else if (Platform.isIOS) {
        // await AppSettings.openAppSettings(type: AppSettingsType.location);
      }
    } else if (await Permission.locationWhenInUse.request().isDenied) {
      print("Location3c");
      setState(() {});
    }
  }

  Future<void> getNotificationsPermissions() async {
    if (await Permission.notification.request().isGranted) {
      setState(() {});
    } else if (await Permission.notification.request().isPermanentlyDenied) {
      await openAppSettings();
    } else if (await Permission.notification.request().isDenied) {
      setState(() {});
    }
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    switch (_source.keys.toList()[0]) {
      case ConnectivityResult.mobile:
        connection = 'Online';
        break;
      case ConnectivityResult.wifi:
        connection = 'Online';
        break;
      case ConnectivityResult.none:
      default:
        connection = 'Offline';
    }
    super.didChangeDependencies();
    precacheImage(splashImage.image, context);
  }

  @override
  Widget build(BuildContext context) {
    switch (_source.keys.toList()[0]) {
      case ConnectivityResult.mobile:
        connection = 'Online';
        break;
      case ConnectivityResult.wifi:
        connection = 'Online';
        break;
      case ConnectivityResult.none:
      default:
        connection = 'Offline';
    }

    return (connection == 'Online')
        ? SafeArea(
          top: false,
          bottom: Platform.isIOS ? false : true,
          child: Scaffold(
            resizeToAvoidBottomInset: true,
            body: Consumer<SplashVersionNotifier>(
              builder: (context, value, child) {
                return Container(
                  alignment: Alignment.center,
                  child: Container(
                    alignment: Alignment.center,
                    height: 300,
                    width: 300,
                    child: splashImage,
                  ),
                );
              },
            ),
          ),
        )
        : NoNetwork(context);
  }
}
