import 'package:art_sweetalert/art_sweetalert.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gap/gap.dart';
import 'package:go_router/go_router.dart';
import 'package:grocery_app/src/common_widget/network_image.dart';
import 'package:grocery_app/src/core/routes/routes.dart';
import 'package:grocery_app/src/logic/provider/bottom_navbar_provider.dart';
import 'package:grocery_app/src/logic/provider/home_provider.dart';
import 'package:grocery_app/src/logic/provider/profile_provider.dart';
import 'package:grocery_app/src/ui/card_checkout/card_checkout_screen.dart';
import 'package:grocery_app/src/ui/edit_profile/edit_profile_screen.dart';

import 'package:grocery_app/src/ui/mapscreen/map_screen.dart';
import 'package:grocery_app/src/ui/message/message_screen.dart';
import 'package:grocery_app/src/ui/notification/notification_screen.dart';
import 'package:grocery_app/src/ui/rating_review/rating_review_screen.dart';
import 'package:grocery_app/src/ui/static_page/tersandconditions.dart';
import 'package:grocery_app/src/ui/widgets/custom_text_field.dart';
import 'package:grocery_app/src/ui/widgets/elevated_button.dart';
import 'package:grocery_app/utils/constants/color_constant.dart';
import 'package:grocery_app/utils/constants/shared_pref_utils.dart';
import 'package:grocery_app/utils/constants/string_constant.dart';
import 'package:grocery_app/utils/extensions/extensions.dart';
import 'package:grocery_app/utils/extensions/uicontext.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

  @override
  State<ProfileScreen> createState() => _ProfileScreenState();
}

class _ProfileScreenState extends State<ProfileScreen> {
  var top = 0.0;

  @override
  void initState() {
    Provider.of<ProfileProvider>(context, listen: false).getProfile(context);
    getUserDetails();
    super.initState();
  }

  getUserDetails() async {
    APPSTRING.userName = (await SharedPrefUtils.getFirstName())!;
    APPSTRING.emailName = (await SharedPrefUtils.getUserEmail())!;
    APPSTRING.userProfile = (await SharedPrefUtils.getUserProfile())!;
    APPSTRING.userLastName = (await SharedPrefUtils.getLastName())!;
  }

  final _formKey = GlobalKey<FormState>();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _confirmPasswordController =
      TextEditingController();

  bool _isPasswordVisible = false;
  bool _isConfirmPasswordVisible = false;

  @override
  void dispose() {
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    print("jdfgkjhgjh  ${APPSTRING.userProfile}");
    return Scaffold(
      body: NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return <Widget>[
            Consumer<ProfileProvider>(builder: (context, provider, child) {
              return SliverAppBar(
                expandedHeight: 180.0,
                floating: false,
                pinned: true,
                backgroundColor: Colors.white,
                leading: const SizedBox(),
                flexibleSpace: LayoutBuilder(builder:
                    (BuildContext context, BoxConstraints constraints) {
                  top = constraints.biggest.height;

                  return FlexibleSpaceBar(
                      centerTitle: true,
                      title: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          top > 100
                              ? Text(
                                  "My  Profile",
                                  style:
                                      context.customExtraBold(Colors.white, 14),
                                )
                              : const SizedBox(),

                          const SizedBox(
                            height: 30,
                          ),
                          //Spacer(),
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              const SizedBox(
                                width: 15,
                              ),
                              Stack(
                                children: [
                                  AppNetworkImage(
                                    height: top < 150 ? 30 : 50,
                                    width: top < 150 ? 30 : 50,
                                    imageUrl: provider.profile ?? "",
                                    radius: 90,
                                    backGroundColor: Colors.white,
                                    boxFit: BoxFit.fill,
                                  ),
                                ],
                              ),
                              const SizedBox(
                                width: 15,
                              ),
                              if (provider.name.isNotEmpty) ...{
                                Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Text(
                                      provider.name ?? " ",
                                      style: context.customExtraBold(
                                          top < 100
                                              ? Colors.black
                                              : Colors.white,
                                          14),
                                    ),
                                    Text(
                                      provider.email,
                                      style: context.customRegular(
                                          top < 100
                                              ? Colors.black
                                              : Colors.white,
                                          10),
                                    )
                                  ],
                                ),
                              } else ...{
                                InkWell(
                                  onTap: () {
                                    context.push(MyRoutes.SIGNUP);
                                  },
                                  child: Text(
                                    " ",
                                    style: context.customExtraBold(
                                        top < 100 ? Colors.blue : Colors.blue,
                                        14),
                                  ),
                                )
                              },
                              const SizedBox(
                                width: 15,
                              ),
                            ],
                          ),
                        ],
                      ),
                      background: Container(
                        height: 200,
                        decoration: BoxDecoration(
                            color: APPCOLOR.lightGreen,
                            borderRadius: const BorderRadius.only(
                                bottomLeft: Radius.circular(30),
                                bottomRight: Radius.circular(30))),
                      ));
                }),
              );
            })
          ];
        },
        body: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    const SizedBox(
                      height: 10,
                    ),
                    ListTile(
                      onTap: () {
                        Navigator.of(context).push(MaterialPageRoute(
                          builder: (context) {
                            return EditProfileScreen();
                          },
                        ));
                      },
                      leading: Icon(MdiIcons.pencilBoxOutline),
                      title: const Text('Edit Profile'),
                      trailing: Icon(MdiIcons.chevronRight),
                    ),
                    ListTile(
                      onTap: () {
                        _showBottomSheet(context);
                      },
                      leading: Icon(MdiIcons.lockOutline),
                      title: const Text('Change Password'),
                      trailing: Icon(MdiIcons.chevronRight),
                    ),
                    // ListTile(
                    //   onTap: () {
                    //     // Navigator.of(context).push(MaterialPageRoute(
                    //     //   builder: (context) {
                    //     //     return const CardCheckoutScreen();
                    //     //   },
                    //     // ));
                    //   },
                    //   leading: Icon(MdiIcons.cardOutline),
                    //   title: const Text('Payment Method'),
                    //   trailing: Icon(MdiIcons.chevronRight),
                    // ),
                    ListTile(
                      onTap: () {
                        context.push(MyRoutes.MYORDER);
                      },
                      leading: Icon(MdiIcons.cubeOutline),
                      title: const Text('My Order'),
                      trailing: Icon(MdiIcons.chevronRight),
                    ),
                    // ListTile(
                    //   onTap: () {
                    //     Navigator.of(context).push(MaterialPageRoute(
                    //       builder: (context) {
                    //         return const NotificationScreen();
                    //       },
                    //     ));
                    //   },
                    //   leading: Icon(MdiIcons.bellOutline),
                    //   title: const Text('Notifications'),
                    //   trailing: Icon(MdiIcons.chevronRight),
                    // ),
                    // ListTile(
                    //   onTap: () {
                    //     Navigator.of(context).push(MaterialPageRoute(
                    //       builder: (context) {
                    //         return const RatingReviewScreen();
                    //       },
                    //     ));
                    //   },
                    //   leading: Icon(MdiIcons.starOutline),
                    //   title: const Text('Rating & Review'),
                    //   trailing: Icon(MdiIcons.chevronRight),
                    // ),
                    // ListTile(
                    //   onTap: () {
                    //     Navigator.of(context).push(MaterialPageRoute(
                    //       builder: (context) {
                    //         return const MessageScreen();
                    //       },
                    //     ));
                    //   },
                    //   leading: Icon(MdiIcons.messageOutline),
                    //   title: const Text('Driver Message'),
                    //   trailing: Icon(MdiIcons.chevronRight),
                    // ),

                    ListTile(
                      onTap: () {
                        context.push(MyRoutes.PRIVACY);
                      },
                      leading: Icon(MdiIcons.shieldCheckOutline),
                      title: const Text('Privacy Policy'),
                      trailing: Icon(MdiIcons.chevronRight),
                    ),
                    ListTile(
                      onTap: () {
                        context.push(MyRoutes.TERMANDCONDITIONS);
                      },
                      leading: Icon(MdiIcons.noteTextOutline),
                      title: const Text('Term & Conditions'),
                      trailing: Icon(MdiIcons.chevronRight),
                    ),
                    // ListTile(
                    //   onTap: () {},
                    //   leading: Icon(MdiIcons.basketOutline),
                    //   title: const Text('Grocery List'),
                    //   trailing: Icon(MdiIcons.chevronRight),
                    // ),
                  ],
                ),
              ),
            ),
            InkWell(
              onTap: () {
                Provider.of<ProductProvider>(context, listen: false)
                    .customerLogOut(context);
              },
              child: Container(
                margin: const EdgeInsets.only(
                    left: 15, right: 15, top: 10, bottom: 10),
                height: 50,
                width: MediaQuery.sizeOf(context).width,
                decoration: BoxDecoration(
                    color: APPCOLOR.lightGreen,
                    borderRadius: BorderRadius.circular(10)),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Icon(
                      MdiIcons.logout,
                      color: Colors.white,
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    Text(
                      "Logout",
                      style: context.customMedium(Colors.white, 16),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  
  void _showBottomSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          decoration: BoxDecoration(
            border: Border.all(color: context.appColor.greyColor400),
            color: context.appColor.whiteColor,
            borderRadius: BorderRadius.all(Radius.circular(5.0)),
          ),
          padding: EdgeInsets.all(20.w),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // Centered App Logo

              Align(
                alignment: Alignment.center,
                child: Text('Change Password', style: context.subTitleStyle),
              ),

              Align(
                alignment: Alignment.center,
                child: Container(
                  width: 300,
                  child: Text('Enter your new password',
                      textAlign: TextAlign.center,
                      style:
                          context.subTitleTextStyle.copyWith(fontSize: 13.sp)),
                ),
              ),
              Form(
                key: _formKey,
                child: Column(
                  children: [
                    // Password Field
                    CustomTextField(
                      controller: _passwordController,
                      obscureText: !_isPasswordVisible,
                      validator: (val) {
                        if (val == null || val.isEmpty) {
                          return "Please enter a password";
                        } else if (val.length < 6) {
                          return "Password must be at least 6 characters long";
                        }
                        return null;
                      },
                      maxLength: 64,
                      counterWidget: const Offstage(),
                      hintText: "Enter password",
                      fillColor: context.appColor.greyColor100,
                      suffix: IconButton(
                        icon: Icon(
                          _isPasswordVisible
                              ? Icons.visibility
                              : Icons.visibility_off,
                        ),
                        onPressed: () {
                          setState(() {
                            _isPasswordVisible = !_isPasswordVisible;
                          });
                        },
                      ),
                    ),
                    Gap(10.h),

                    // Confirm Password Field
                    CustomTextField(
                      controller: _confirmPasswordController,
                      obscureText: !_isConfirmPasswordVisible,
                      validator: (val) {
                        if (val == null || val.isEmpty) {
                          return "Please confirm your password";
                        } else if (val != _passwordController.text) {
                          return "Passwords do not match";
                        }
                        return null;
                      },
                      maxLength: 64,
                      counterWidget: const Offstage(),
                      hintText: "Confirm password",
                      fillColor: context.appColor.greyColor100,
                      suffix: IconButton(
                        icon: Icon(
                          _isConfirmPasswordVisible
                              ? Icons.visibility
                              : Icons.visibility_off,
                        ),
                        onPressed: () {
                          setState(() {
                            _isConfirmPasswordVisible =
                                !_isConfirmPasswordVisible;
                          });
                        },
                      ),
                    ),
                  ],
                ),
              ),
              Gap(20.h),
              Center(
                child: SizedBox(
                  child: SizedBox(
                    width: double.infinity,
                    child: ButtonElevated(
                        text: 'Change Password',
                        onPressed: () {
                          Navigator.pop(context);
                          ArtSweetAlert.show(
                              context: context,
                              artDialogArgs: ArtDialogArgs(
                                  type: ArtSweetAlertType.success,
                                  title: "Password Reset Successful",
                                  text: ""));
                        },
                        backgroundColor: context.appColor.primarycolor),
                  ),
                ),
              ),
              Gap(10.h),
            ],
          ),
        );
      },
    );
  }
}
