import 'package:clipboard/clipboard.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:frontend_eccp_mobile/app/core/constants/constants.dart';
import 'package:frontend_eccp_mobile/app/core/constants/enum/snackbar_type_enum.dart';
import 'package:frontend_eccp_mobile/app/core/di/injection.dart';
import 'package:frontend_eccp_mobile/app/core/handler/auth_handler.dart';
import 'package:frontend_eccp_mobile/app/core/navigation/app_navigator.dart';
import 'package:frontend_eccp_mobile/app/core/navigation/app_routes.dart';
import 'package:frontend_eccp_mobile/app/core/notification/fcm_token_manager.dart';
import 'package:frontend_eccp_mobile/app/core/utils/show_message.dart';
import 'package:frontend_eccp_mobile/app/core/utils/token_manager.dart';
import 'package:frontend_eccp_mobile/app/core/widgets/app_button.dart';
import 'package:frontend_eccp_mobile/app/core/widgets/layout/app_screen.dart';
import 'package:frontend_eccp_mobile/modules/profile/bloc/logout/logout_cubit.dart';
import 'package:frontend_eccp_mobile/modules/profile/bloc/logout/logout_state.dart';
import 'package:frontend_eccp_mobile/modules/profile/presentation/widgets/profile_header_card.dart';
import 'package:frontend_eccp_mobile/modules/profile/presentation/widgets/profile_menu_section.dart';
import 'package:iconsax_plus/iconsax_plus.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

class ProfilePage extends StatelessWidget {
  const ProfilePage({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) => getIt<LogoutCubit>(),
      child: const ProfileUI(),
    );
  }
}

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

  @override
  State<ProfileUI> createState() => _ProfileUIState();
}

class _ProfileUIState extends State<ProfileUI> {
  final RefreshController _refreshController = RefreshController();

  Future<void> _onRefresh() async {
    await Future<void>.delayed(const Duration(milliseconds: 800));
    _refreshController.refreshCompleted();
  }

  bool get isTablet => MediaQuery.of(context).size.width > 600;

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<LogoutCubit, LogoutState>(
      listener: (context, state) async {
        if (state is LogoutLoading) return;

        await TokenManager.clearToken();

        if (!context.mounted) return;

        await AppNavigator.clearAndPush(
          context,
          AppRoutes.login,
        );
      },
      builder: (context, state) {
        return AppScreen(
          title: 'PROFIL',
          backgroundColor: AppColors.neutral50,
          refreshController: _refreshController,
          enablePullDown: true,
          onRefresh: _onRefresh,
          refreshHeader: const ClassicHeader(),
          body: Center(
            child: ConstrainedBox(
              constraints: const BoxConstraints(maxWidth: 900),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  AppSpacing.h16,

                  const Padding(
                    padding: AppPadding.h16,
                    child: ProfileHeaderCard(),
                  ),

                  AppSpacing.h24,

                  ProfileMenuSection(
                    title: 'Personal Information',
                    items: [
                      ProfileMenuItem(
                        icon: IconsaxPlusLinear.personalcard,
                        label: 'My Details',
                        iconColor: AppColors.neutral900,
                      ),
                      ProfileMenuItem(
                        icon: IconsaxPlusLinear.lock,
                        label: 'Change Password',
                        iconColor: AppColors.neutral900,
                      ),
                      ProfileMenuItem(
                        icon: IconsaxPlusLinear.notification_1,
                        label: 'Copy FCM Token',
                        iconColor: AppColors.neutral900,
                        onTap: () async {
                          final token = await FcmTokenManager.getToken();
                          await FlutterClipboard.copy(token ?? '');
                          if (!context.mounted) return;
                          showMessage(
                            context,
                            'FCM Token copied : \n${token ?? ''}',
                            SnackBarType.success,
                          );
                        },
                      ),
                    ],
                  ),
                  AppSpacing.h16,

                  Padding(
                    padding: AppPadding.p16,
                    child: AppButton(
                      height: 48,
                      paddingVertical: 0,
                      label: '',
                      customContent: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          const Icon(
                            Icons.logout_rounded,
                            color: Colors.white,
                          ),
                          AppSpacing.w6,
                          Text(
                            'Log Out',
                            style: AppTextStyles.label.copyWith(
                              color: AppColors.neutralWhite,
                            ),
                          ),
                        ],
                      ),
                      isExpanded: true,
                      onPressed: () async {
                        await AuthHandler.logout(context);
                      },
                      isLoading: state is LogoutLoading,
                    ),
                  ),

                  AppSpacing.h32,
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}
