import 'package:flutter/material.dart';
import 'package:top_news_app/helper/helper.dart';
import 'package:top_news_app/model/user.dart';
import 'package:top_news_app/screen/bookmark_screen.dart';
import 'package:top_news_app/screen/change_password.dart';
import 'package:top_news_app/screen/languages_screen.dart';
import 'package:top_news_app/screen/update_profile.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';
import '../localization/localization.dart';
import '../model/auth.dart';
import '../providers/theme_provider.dart';
import '../repos/exception_handlers.dart';
import '../services/auth_service.dart';
import '../services/storage_service.dart';

class SettingScreen extends StatefulWidget {
  const SettingScreen({super.key});
  @override
  State<SettingScreen> createState() => _SettingScreenState();
}

class _SettingScreenState extends State<SettingScreen> {
   bool isDark = false;
   bool loading = true;

   var auth = Auth();
   User user = User();
   bool isAuth = false;
   var storage = StorageService();
   final AuthService _authService = AuthService();


   _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(() {
       loading = false;
     });
   }

   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);
       }

     }
   }


   toggleTheme(options) async{
    Provider.of<ThemeProvider>(context, listen: false).changeTheme(options ?? 'system');
     setState(() {

     });
  }

  @override
  void initState() {
    super.initState();
    getAuthData();
    getTheme();
    getUserDetails();

  }

  getTheme() async{
    Provider.of<ThemeProvider>(context, listen: false).currentTheme;
  }


  @override
  Widget build(BuildContext context) {

    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: loading ? const Center(
        child: CircularProgressIndicator(),
      ) : ListView(
        children: [
          customSizeBox(10),
         isAuth ? Padding(
            padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 16, 12),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '${auth.name}',
                      style: GoogleFonts.robotoSerif(
                        color: primaryColors,
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(vertical: 10),
                      child: Text(
                        '${auth.email}',
                        style: GoogleFonts.robotoSerif(
                          color: Theme.of(context).iconTheme.color,
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ],
                ),
                Container(
                  width: 50,
                  height: 50,
                  clipBehavior: Clip.antiAlias,
                  decoration: const BoxDecoration(
                    shape: BoxShape.circle,
                  ),
                  child: Image.network('${auth.avatar}',fit: BoxFit.fitWidth,),
                ),
              ],
            ),
          ) : Container(),
          Padding(
            padding: const EdgeInsetsDirectional.fromSTEB(0, 0, 0, 1),
            child: Container(
              width: double.infinity,
              decoration: BoxDecoration(

                boxShadow: [
                  BoxShadow(
                    blurRadius: 0,
                    color: Theme.of(context).scaffoldBackgroundColor,
                    offset: const Offset(0, 1),
                  )
                ],
              ),
              child: Padding(
                padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 0, 12),
                child: Text(
                  getTranslated(context, 'My Account Information') ?? 'My Account Information',
                  style: GoogleFonts.robotoSerif(
                    color: Theme.of(context).iconTheme.color,
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ),
          ),
          customSizeBox(10),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 2),
            width: double.infinity,
            height: 70,
            decoration: BoxDecoration(
              border: Border.all(color: Theme.of(context).dividerColor,width: 2),
              borderRadius: const BorderRadius.all(Radius.circular(8)),
            ),
            child: Padding(
              padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 0),
              child: Column(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Row(
                    mainAxisSize: MainAxisSize.max,
                    children: [
                      Text(
                        getTranslated(context, 'Change Password') ?? 'Change Password',
                        style:
                        GoogleFonts.robotoSerif(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      Expanded(
                        child: Align(
                          alignment: const AlignmentDirectional(1.00, 0.00),
                          child: GestureDetector(
                            onTap: (){
                              if(isAuth){
                                Navigator.push(context, MaterialPageRoute(builder: (context)=>const ChangePassword()));
                              }else{
                                dialogLogin(context);
                              }

                            },
                            child: const Icon(
                              Icons.arrow_forward_ios,
                              size: 20,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
          customSizeBox(10),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 2),
            width: MediaQuery.sizeOf(context).width,
            height: 70,
            decoration: BoxDecoration(
              border: Border.all(color: Theme.of(context).dividerColor,width: 2),
              borderRadius: const BorderRadius.all(Radius.circular(8)),
            ),
            child: Padding(
              padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 0),
              child: Column(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Row(
                    mainAxisSize: MainAxisSize.max,
                    children: [
                      Text(
                        getTranslated(context, 'Edit Profile') ?? 'Edit Profile',
                        style: GoogleFonts.robotoSerif(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      Expanded(
                        child: GestureDetector(
                          onTap: (){
                            if(isAuth){
                              Navigator.push(context, MaterialPageRoute(builder: (context)=>UpdateProfile(user: user,)));
                            }else{
                              dialogLogin(context);
                            }

                          },
                          child: const Align(
                            alignment: AlignmentDirectional(1.00, 0.00),
                            child: Icon(
                              Icons.arrow_forward_ios,
                              size: 20,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
          customSizeBox(10),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 2),
            width: double.infinity,
            height: 70,
            decoration: BoxDecoration(
              border: Border.all(color: Theme.of(context).dividerColor,width: 2),
              borderRadius: const BorderRadius.all(Radius.circular(8)),
            ),
            child: Padding(
              padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 0),
              child: Column(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Row(
                    mainAxisSize: MainAxisSize.max,
                    children: [
                      Text(
                        getTranslated(context, 'Bookmark') ?? 'Bookmark',
                        style:
                        GoogleFonts.robotoSerif(

                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      Expanded(
                        child: Align(
                          alignment: const AlignmentDirectional(1.00, 0.00),
                          child: GestureDetector(
                            onTap: (){
                              if(isAuth){
                                Navigator.push(context, MaterialPageRoute(builder: (context)=>const BookMarkScreen()));
                              }else{
                                dialogLogin(context);
                              }

                            },
                            child: const Icon(
                              Icons.arrow_forward_ios,
                              size: 20,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
          customSizeBox(10),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 2),
            width: double.infinity,
            decoration: BoxDecoration(
              boxShadow: [
                BoxShadow(
                  blurRadius: 0,
                  color: Theme.of(context).scaffoldBackgroundColor,
                  offset: const Offset(0, 1),
                )
              ],
            ),
            child: Padding(
              padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 0, 12),
              child: Text(
                getTranslated(context, 'Settings') ?? 'Settings',
                style: GoogleFonts.robotoSerif(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ),
          customSizeBox(10),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 2),
            width: MediaQuery.sizeOf(context).width,
            height: 70,
            decoration: BoxDecoration(
              border: Border.all(color: Theme.of(context).dividerColor,width: 2),
              borderRadius: const BorderRadius.all(Radius.circular(8)),
            ),
            child: GestureDetector(
              onTap: (){
                if(isAuth){
                  Navigator.push(context, MaterialPageRoute(builder: (context)=>const LanguagesScreen()));
                }else{
                  dialogLogin(context);
                }

              },
              child: Padding(
                padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 0),
                child: Column(
                  mainAxisSize: MainAxisSize.max,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Row(
                      mainAxisSize: MainAxisSize.max,
                      children: [
                        Text(
                          getTranslated(context, 'Languages') ?? 'Languages',
                          style: GoogleFonts.robotoSerif(
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        const Expanded(
                          child: Align(
                            alignment: AlignmentDirectional(1.00, 0.00),
                            child: Icon(
                              Icons.arrow_forward_ios,
                              size: 20,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
          customSizeBox(10),
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 18,vertical: 8),
            width: double.infinity,
            height: 50,
            decoration: BoxDecoration(
              color: const Color(0xFFF1F4F8),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(
                color: Colors.transparent,
                width: 1,
              ),
            ),
            child: Padding(
              padding: const EdgeInsetsDirectional.fromSTEB(4, 4, 4, 4),
              child: Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Expanded(
                    child: InkWell(
                      splashColor: Colors.transparent,
                      focusColor: Colors.transparent,
                      hoverColor: Colors.transparent,
                      highlightColor: Colors.transparent,
                      onTap: () async {
                        toggleTheme('light');
                      },
                      child: Container(
                        width: 115,
                        height: 100,
                        decoration: BoxDecoration(
                          color: Theme.of(context).brightness ==
                              Brightness.light
                              ? Colors.white
                              : const Color(0xFFF1F4F8),
                          borderRadius: BorderRadius.circular(10),
                          border: Border.all(
                            color: Theme.of(context).brightness ==
                                Brightness.light
                                ? Colors.transparent
                                : const Color(0xFFF1F4F8),
                            width: 1,
                          ),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.max,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.wb_sunny_rounded,
                              color: Theme.of(context).brightness ==
                                  Brightness.light
                                  ? const Color(0xFF15161E)
                                  : const Color(0xFF606A85),
                              size: 16,
                            ),
                            Padding(
                              padding: const EdgeInsetsDirectional.fromSTEB(
                                  4, 0, 0, 0),
                              child: Text(
                                '${getTranslated(context, 'Light') ?? 'Light'} ',
                                style: GoogleFonts.robotoSerif(

                                  color: Theme.of(context).brightness ==
                                      Brightness.light
                                      ? const Color(0xFF15161E)
                                      : const Color(0xFF606A85),
                                  fontSize: 14,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                  Expanded(
                    child: InkWell(
                      splashColor: Colors.transparent,
                      focusColor: Colors.transparent,
                      hoverColor: Colors.transparent,
                      highlightColor: Colors.transparent,
                      onTap: () async {
                        toggleTheme('dark');
                      },
                      child: Container(
                        width: 115,
                        height: 100,
                        decoration: BoxDecoration(
                          color: Theme.of(context).brightness ==
                              Brightness.dark
                              ? Colors.white
                              : const Color(0xFFF1F4F8),
                          borderRadius: BorderRadius.circular(10),
                          border: Border.all(
                            color: Theme.of(context).brightness ==
                                Brightness.dark
                                ? Colors.transparent
                                : const Color(0xFFF1F4F8),
                            width: 1,
                          ),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.max,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.nightlight_round,
                              color: Theme.of(context).brightness ==
                                  Brightness.dark
                                  ? const Color(0xFF15161E)
                                  : const Color(0xFF606A85),
                              size: 16,
                            ),
                            Padding(
                              padding: const EdgeInsetsDirectional.fromSTEB(
                                  4, 0, 0, 0),
                              child: Text(
                                getTranslated(context, 'Dark') ?? 'Dark',
                                style: GoogleFonts.robotoSerif(
                                  color: Theme.of(context).brightness ==
                                      Brightness.dark
                                      ? const Color(0xFF15161E)
                                      : const Color(0xFF606A85),
                                  fontSize: 14,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          customSizeBox(10),
        isAuth ?  Padding(
            padding: const EdgeInsetsDirectional.fromSTEB(0, 36, 0, 0),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                GestureDetector(
                  onTap: () {
                    _logoutConfirm(context);
                  },
                  child: Container(
                    width: 130,
                    height: 50,
                    padding: const EdgeInsetsDirectional.fromSTEB(0, 0, 0, 0),
                    decoration: BoxDecoration(
                      color: Theme.of(context).primaryColor,
                      border: Border.all(
                          color: const Color(0xFFE5E7EB),
                          width: 2,
                      ),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Center(
                      child: Text(getTranslated(context, 'Log Out') ?? 'Log Out',style: GoogleFonts.robotoSerif(
                        color: Colors.white,
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),),
                    ),


                  ),
                ),
              ],
            ),
          ) : Container(),
        ],
      ),
    );
  }
}
