import 'dart:io';

import 'package:bootstrap_icons/bootstrap_icons.dart';
import 'package:english_learning/core/services/constants.dart';
import 'package:english_learning/core/widgets/custom_snackbar.dart';
import 'package:english_learning/features/auth/provider/user_provider.dart';
import 'package:english_learning/features/auth/screens/signin/signin_screen.dart';
import 'package:english_learning/features/settings/modules/change_password/screens/change_password_screen.dart';
import 'package:english_learning/features/settings/modules/edit_profile/screens/edit_profile_screen.dart';
import 'package:english_learning/core/utils/styles/theme.dart';
import 'package:english_learning/features/settings/modules/logout/screens/logout_confirmation.dart';
import 'package:english_learning/features/settings/modules/report_issue/screens/report_issue_screen.dart';
import 'package:english_learning/features/settings/widgets/menu_item.dart';
import 'package:english_learning/features/settings/widgets/user_avatar.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

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

  @override
  State<SettingsScreen> createState() => _SettingsScreenState();
}

class _SettingsScreenState extends State<SettingsScreen> {
  // @override
  // void initState() {
  //   super.initState();
  //   WidgetsBinding.instance.addPostFrameCallback((_) {
  //     Provider.of<UserProvider>(context, listen: false).refreshUserData();
  //   });
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.bgSoftColor,
      body: Consumer<UserProvider>(builder: (context, userProvider, child) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Stack(
              children: [
                Container(
                  width: double.infinity,
                  height: 210,
                  decoration: BoxDecoration(
                    gradient: AppColors.gradientTheme,
                    borderRadius: const BorderRadius.only(
                      bottomLeft: Radius.circular(24),
                      bottomRight: Radius.circular(24),
                    ),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.only(
                        top: 71.0, left: 26, right: 16.0, bottom: 19.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Row(
                          children: [
                            Row(
                              children: [
                                UserAvatar(
                                  radius: 60,
                                  pictureUrl: userProvider.userData?['PICTURE'],
                                  baseUrl: '${baseUrl}api/uploads/avatar/',
                                  onImageSelected: (File image) {
                                    userProvider.setSelectedImage(image);
                                  },
                                  selectedImage: userProvider.selectedImage,
                                  isLoading: userProvider.isLoading,
                                ),
                                const SizedBox(width: 28),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      userProvider.userData?['NAME_USERS'] ??
                                          'Loading...',
                                      style:
                                          AppTextStyles.whiteTextStyle.copyWith(
                                        fontSize: 18,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                    const SizedBox(height: 8),
                                    Text(
                                      userProvider.userData?['EMAIL'] ??
                                          'Loading...',
                                      style:
                                          AppTextStyles.whiteTextStyle.copyWith(
                                        fontSize: 14,
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            )
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 24),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: Container(
                decoration: BoxDecoration(
                  color: AppColors.whiteColor,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Column(
                  children: [
                    MenuItem(
                      isFirst: true,
                      icon: BootstrapIcons.person_gear,
                      text: 'Edit Profile',
                      onPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const EditProfileScreen(),
                          ),
                        );
                        Provider.of<UserProvider>(context, listen: false)
                            .refreshUserData();
                      },
                    ),
                    const Divider(
                      color: AppColors.bgSoftColor,
                      height: 1,
                      thickness: 2,
                    ),
                    MenuItem(
                      icon: BootstrapIcons.shield_lock,
                      text: 'Change Password',
                      onPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const ChangePasswordScreen(),
                          ),
                        );
                      },
                    ),
                    const Divider(
                      color: AppColors.bgSoftColor,
                      height: 1,
                      thickness: 2,
                    ),
                    MenuItem(
                      icon: BootstrapIcons.exclamation_circle,
                      text: 'Report an Issue',
                      onPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const ReportIssueScreen(),
                          ),
                        );
                      },
                    ),
                    const Divider(
                      color: AppColors.bgSoftColor,
                      height: 1,
                      thickness: 2,
                    ),
                    MenuItem(
                      isLast: true,
                      icon: BootstrapIcons.box_arrow_right,
                      iconColor: AppColors.redColor,
                      text: 'Logout',
                      textColor: AppColors.redColor,
                      onPressed: () {
                        showDialog(
                          context: context,
                          builder: (BuildContext context) {
                            return LogoutConfirmation(
                              onSubmit: () async {
                                final success = await userProvider.logout();
                                if (success) {
                                  Navigator.of(context).pushAndRemoveUntil(
                                    MaterialPageRoute(
                                        builder: (context) => SigninScreen()),
                                    (Route<dynamic> route) => false,
                                  );
                                } else {
                                  CustomSnackBar.show(
                                    context,
                                    message: 'Logout failed. Please try again.',
                                    isError: true,
                                  );
                                }
                              },
                            );
                          },
                        );
                      },
                    ),
                  ],
                ),
              ),
            )
          ],
        );
      }),
    );
  }
}
