
import 'dart:io';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:top_news_app/helper/custom_appbar.dart';
import 'package:top_news_app/helper/helper.dart';
import 'package:top_news_app/screen/category_screen.dart';
import 'package:top_news_app/screen/home_screen.dart';
import 'package:top_news_app/screen/polling_screen.dart';
import 'package:top_news_app/screen/setting_screen.dart';
import 'package:top_news_app/widget/drawer_widget.dart';

import '../services/storage_service.dart';

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

  @override
  State<MainScreen> createState() => _MainScreenState();

}

class _MainScreenState extends State<MainScreen> {
  var scaffoldKEy = GlobalKey<ScaffoldState>();
  StorageService localService = StorageService();

  Future _initializeNotification() async {

    int id = await localService.getUserId() ?? 0;

      final firebaseMessaging = FirebaseMessaging.instance;
      await firebaseMessaging.requestPermission(
        alert: true,
        announcement: false,
        badge: true,
        carPlay: false,
        criticalAlert: false,
        provisional: false,
        sound: true,
      );
    if(id != 0){
      firebaseMessaging.subscribeToTopic(
          'for-user-$id');
    }
      firebaseMessaging.subscribeToTopic(
          'for-only-web-customer');
      firebaseMessaging.subscribeToTopic(
          'for-all-user');
      firebaseMessaging.subscribeToTopic(
          'for-only-mobile-user');





      FirebaseMessaging.onMessage.listen((RemoteMessage message) {

      });


      FirebaseMessaging.onMessageOpenedApp.listen((message) {
        Navigator.pushReplacementNamed(context, '/main-screen');

      });

    }


  @override
  void initState() {
    super.initState();
  }
  var currentIndex = 0;
  @override
  Widget build(BuildContext context) {
    _initializeNotification();
    List<Widget> widgetOptions = <Widget>[
      const HomeScreen(),
      const CategoryScreen(),
      const PollingScreen(),
      const SettingScreen(),
    ];
    double displayWidth = MediaQuery.of(context).size.width;
    return WillPopScope(
      onWillPop: () async {
        final shouldPop = await showDialog<bool?>(
          context: context,
          builder: (context) =>  AlertDialog(
            title:  const Text('Are you sure ?'),
            content: const Text( 'Do you want to exit from app'),
            buttonPadding: const EdgeInsets.only(bottom: 20, left: 15),
            actions: <Widget>[
              TextButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: const Text('Cancel',style: TextStyle(color: primaryColors),),
              ),
              const SizedBox(height: 16),
              TextButton(
                onPressed: () => exit(0),
                child:  const Text('Exit',style: TextStyle(color: Colors.red),),
              ),
            ],
          ),
        );
        return shouldPop ?? false;
      },
      child: SafeArea(

        child: Scaffold(
          key: scaffoldKEy,
          appBar: customAppBar(
              'image',
              scaffoldKEy,context),
          drawer: const DrawerWidget(key: null,),
          body: widgetOptions.elementAt(currentIndex),
          bottomNavigationBar: Container(
            margin: EdgeInsets.all(displayWidth * .05),
            height: displayWidth * .155,
            decoration: BoxDecoration(
              color: Theme.of(context).scaffoldBackgroundColor,
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(.1),
                  blurRadius: 30,
                  offset: const Offset(0, 10),
                ),
              ],
              borderRadius: BorderRadius.circular(50),
            ),
            child: ListView.builder(
              itemCount: 4,
              scrollDirection: Axis.horizontal,
              padding: EdgeInsets.symmetric(horizontal: displayWidth * .02),
              itemBuilder: (context, index) => InkWell(
                onTap: () {
                  setState(() {
                    currentIndex = index;
                    HapticFeedback.lightImpact();
                  });
                },
                splashColor: Colors.transparent,
                highlightColor: Colors.transparent,
                child: Stack(
                  children: [
                    AnimatedContainer(
                      duration: const Duration(seconds: 1),
                      curve: Curves.fastLinearToSlowEaseIn,
                      width: index == currentIndex
                          ? displayWidth * .32
                          : displayWidth * .18,
                      alignment: Alignment.center,
                      child: AnimatedContainer(
                        duration: const Duration(seconds: 1),
                        curve: Curves.fastLinearToSlowEaseIn,
                        height: index == currentIndex ? displayWidth * .12 : 0,
                        width: index == currentIndex ? displayWidth * .32 : 0,
                        decoration: BoxDecoration(
                          color: index == currentIndex
                              ? Colors.blueAccent.withOpacity(.2)
                              : Colors.transparent,
                          borderRadius: BorderRadius.circular(50),
                        ),
                      ),
                    ),
                    AnimatedContainer(
                      duration: const Duration(seconds: 1),
                      curve: Curves.fastLinearToSlowEaseIn,
                      width: index == currentIndex
                          ? displayWidth * .31
                          : displayWidth * .18,
                      alignment: Alignment.center,
                      child: Stack(
                        children: [
                          Row(
                            children: [
                              AnimatedContainer(
                                duration: const Duration(seconds: 1),
                                curve: Curves.fastLinearToSlowEaseIn,
                                width:
                                index == currentIndex ? displayWidth * .13 : 0,
                              ),
                              AnimatedOpacity(
                                opacity: index == currentIndex ? 1 : 0,
                                duration: const Duration(seconds: 1),
                                curve: Curves.fastLinearToSlowEaseIn,
                                child: Text(
                                  index == currentIndex
                                      ? listOfStrings[index]
                                      : '',
                                  style: const TextStyle(
                                    color: Colors.blueAccent,
                                    fontWeight: FontWeight.w600,
                                    fontSize: 15,
                                  ),
                                ),
                              ),
                            ],
                          ),
                          Row(
                            children: [
                              AnimatedContainer(
                                duration: const Duration(seconds: 1),
                                curve: Curves.fastLinearToSlowEaseIn,
                                width:
                                index == currentIndex ? displayWidth * .03 : 20,
                              ),
                              Icon(
                                listOfIcons[index],
                                size: displayWidth * .076,
                                color: index == currentIndex
                                    ? Colors.blueAccent
                                    : Theme.of(context).iconTheme.color,
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),

        ),
      ),
    );
  }
}
List<IconData> listOfIcons = [
  Icons.home_outlined,
  Icons.category_outlined,
  Icons.poll_outlined,
  Icons.settings,
];

List<String> listOfStrings = [
  'Explore',
  'Category',
  'Polling',
  'Setting',
];