
import 'package:flutter/material.dart';
import 'package:top_news_app/localization/localization.dart';
import 'package:top_news_app/model/auth.dart';
import 'package:top_news_app/screen/authors_screen.dart';
import 'package:top_news_app/screen/categories_screen.dart';
import 'package:top_news_app/screen/languages_screen.dart';
import 'package:top_news_app/services/auth_service.dart';
import 'package:top_news_app/services/storage_service.dart';
import '../helper/helper.dart';
import '../model/user.dart';
import '../repos/exception_handlers.dart';


class DrawerWidget extends StatefulWidget {
  const DrawerWidget({Key? key}) : super(key: key);


  @override
  State<DrawerWidget> createState() => _DrawerWidgetState();
}

class _DrawerWidgetState extends State<DrawerWidget> {
 var auth = Auth();
 User user= User();
 bool isAuth = false;
 var storage = StorageService();
 final AuthService _authService = AuthService();



 getUserDetails() async{
   try{
     var authService = AuthService();
     var result = await authService.checkAuth();
     user = User.fromJson(result);

   }catch(e){
     if(isAuth){
       var message = ExceptionHandlers().getExceptionString(e);
       showMessage(message);
     }

   }
 }

  _logoutConfirm(context) {
    return showDialog(
      context: context,
      builder: (context) =>  AlertDialog(
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(32.0))),
        title:   Text(getTranslated(context, 'Are you sure') ?? 'Are you sure'),
        content:   Text(getTranslated(context, 'Do you want to logout from App') ?? 'Do you want to logout from App'),
        actionsPadding: const EdgeInsets.all(28),
        actions: <Widget>[
          GestureDetector(
            onTap: () => Navigator.of(context).pop(false),
            child:  Text(getTranslated(context, 'NO') ?? 'NO'),
          ),
          const SizedBox(height: 16),
          GestureDetector(
            onTap: (){
              _authService.logout();
              storage.removeAuthSharedPreferences();
              Navigator.pop(context);
            },
            child:  Text(getTranslated(context, 'YES') ?? 'YES'),
          ),
        ],
      ),
    );
  }

  getAuthData() async{
    isAuth = (await storage.isAuthInLocal())!;
    if(isAuth){
      auth = await storage.getAuthUserDataFromStorage();
    }
    setState(() {

    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getAuthData();
    getUserDetails();
  }

  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: ListView(
        children: <Widget>[
          buildHeader(
            isAuth: isAuth, 
              onClicked: () {
              Navigator.pop(context);
          }, auth: auth),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Column(
              children: [
                const Divider(color: Colors.white70),
                buildMenuItem(
                  text: getTranslated(context, 'Home') ?? 'Home',
                  icon: Icons.home,
                  onClicked: () {
                    Navigator.pop(context);
                    Navigator.pushReplacementNamed(context, '/main-screen');
                  },
                ),
                buildMenuItem(
                  text: getTranslated(context, 'Categories') ?? 'Categories',
                  icon: Icons.format_align_center_sharp,
                  onClicked: (){
                    Navigator.pop(context);
                    Navigator.push(context, MaterialPageRoute(builder: (context)=>const CategoriesScreens()));
                  },
                ),
                buildMenuItem(
                  text: getTranslated(context, 'Bookmark') ?? 'Bookmark',
                  icon: Icons.bookmark_border,
                  onClicked: () {
                    Navigator.pop(context);
                    Navigator.pushNamed(context, '/bookMark-screen');
                  },
                ),
                buildMenuItem(
                  text: getTranslated(context, 'Authors') ?? 'Authors',
                  icon: Icons.account_circle_outlined,
                  onClicked: () {
                    Navigator.pop(context);
                    Navigator.push(context, MaterialPageRoute(builder: (context)=>const AuthorsScreen()));
                  },
                ),
                isAuth ? buildMenuItem(
                  text: getTranslated(context, 'Languages') ?? 'Languages',
                  icon: Icons.language,
                  onClicked: () {
                    Navigator.pop(context);
                    Navigator.push(context, MaterialPageRoute(builder: (context)=>const LanguagesScreen()));
                  },
                ) : Container(),

                const Divider(color: Colors.white70),
                const SizedBox(height: 24),
                isAuth ?  buildMenuItem(
                  text: getTranslated(context, 'Logout') ??' Logout',
                  icon: Icons.logout,
                  onClicked: () {
                    Navigator.pop(context);
                    _logoutConfirm(context);
                  },
                ) : Container(),
              isAuth ? Container():  buildMenuItem(
                  text: getTranslated(context, 'Login') ?? 'Login',
                  icon: Icons.login,
                  onClicked: () {
                    Navigator.pop(context);
                    Navigator.pushNamed(context, '/email-login');
                  },
                ),
                isAuth ? Container():   buildMenuItem(
                  text: getTranslated(context, 'Register') ?? 'Register',
                  icon: Icons.app_registration,
                  onClicked: () {
                    Navigator.pop(context);
                    Navigator.pushNamed(context, '/sign-up');
                  },
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget buildHeader({
    required bool isAuth,
    required Auth auth,
    required VoidCallback onClicked,
  }) =>
      GestureDetector(
        onTap: onClicked,
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 40),
          child: Row(
            children: [
              const SizedBox(width: 20),
              isAuth ? CircleAvatar(radius: 30, backgroundImage: NetworkImage(auth.avatar!)) : const CircleAvatar(radius: 30,
              child: Icon(Icons.account_circle),),
              const SizedBox(width: 20),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    isAuth ? auth.name! : 'Name',
                    style: TextStyle(
                        fontSize: 20,
                        fontFamily: fontFamily,
                        fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    isAuth ? auth.email! : 'User Email',
                    style: TextStyle(
                        fontSize: 14,
                        fontFamily: fontFamily,
                        fontWeight: FontWeight.w300),
                  ),
                ],
              ),
              const Spacer(),
              const SizedBox(width: 20),
            ],
          ),
        ),
      );

  Widget buildSearchField() {
    const color = Colors.white;

    return TextField(
      style: const TextStyle(color: color),
      decoration: InputDecoration(
        contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 15),
        hintText: 'Search',
        hintStyle: const TextStyle(color: color),
        prefixIcon: const Icon(Icons.search, color: color),
        filled: true,
        fillColor: Colors.white12,
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(5),
          borderSide: BorderSide(color: color.withOpacity(0.7)),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(5),
          borderSide: BorderSide(color: color.withOpacity(0.7)),
        ),
      ),
    );
  }

  Widget buildMenuItem({
    required String text,
    required IconData icon,
    required VoidCallback onClicked,
  }) {
    const hoverColor = Colors.white70;

    return ListTile(
      leading: Icon(icon,color: Theme.of(context).iconTheme.color,size: 26,),
      title: Text(text),
      hoverColor: hoverColor,
      onTap: onClicked,
    );
  }
}