// ignore_for_file: deprecated_member_use_from_same_package, use_build_context_synchronously

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:hoshan/core/gen/assets.gen.dart';
import 'package:hoshan/core/routes/route_generator.dart';
import 'package:hoshan/core/services/api/dio_service.dart';
import 'package:hoshan/core/utils/date_time.dart';
import 'package:hoshan/data/model/empty_states_enum.dart';
import 'package:hoshan/ui/screens/splash/cubit/user_info_cubit.dart';
import 'package:hoshan/ui/theme/colors.dart';
import 'package:hoshan/ui/theme/cubit/theme_mode_cubit.dart';
import 'package:hoshan/ui/theme/responsive.dart';
import 'package:hoshan/ui/theme/text.dart';
import 'package:hoshan/ui/widgets/components/button/circle_icon_btn.dart';
import 'package:hoshan/ui/widgets/sections/empty/empty_states.dart';
import 'package:persian_number_utility/persian_number_utility.dart';
import 'package:flutter/services.dart';

class HomeAppbar extends StatelessWidget implements PreferredSizeWidget {
  static const platform = MethodChannel('webview_channel');

  final BuildContext context;

  const HomeAppbar(this.context, {super.key});

  Future<void> _openWebView() async {
    try {
      await platform.invokeMethod('openWebView');
    } on PlatformException catch (e) {
      debugPrint("Failed to open WebView: '${e.message}'.");
    }
  }

  @override
  Widget build(BuildContext context) {
    return AppBar(
      toolbarHeight: preferredSize.height,
      shadowColor: AppColors.black.defaultShade.withValues(alpha: 0.15),
      elevation: 4,
      title: Flex(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        direction: Axis.horizontal,
        children: [
          Flexible(
            flex: 1,
            child: Row(
              children: [
                // CircleIconBtn(
                //   size: Responsive(context).isMobile() ? 32 : 46,
                //   iconPadding: Responsive(context).isMobile()
                //       ? null
                //       : const EdgeInsets.all(8),
                //   icon: Assets.icon.bold.setting,
                //   color: context.read<ThemeModeCubit>().isDark()
                //       ? AppColors.black[900]
                //       : AppColors.primaryColor[50],
                //   iconColor: Theme.of(context).colorScheme.primary,
                //   onTap: () {
                //     context.go(Routes.setting);
                //   },
                // ),
                // SizedBox(
                //   width: Responsive(context).isMobile() ? 4 : 8,
                // ),
                PopupMenuButton(
                  tooltip: '',
                  splashRadius: 0,
                  onOpened: () async {
                    try {
                      DioService()
                          .sendRequest()
                          .put(DioService.readAllNotifications);
                      final notifs =
                          UserInfoCubit.userInfoModel.notifications!.map(
                        (e) {
                          e.seen = true;
                          return e;
                        },
                      ).toList();
                      UserInfoCubit.userInfoModel.notifications = notifs;
                      context
                          .read<UserInfoCubit>()
                          .changeUser(UserInfoCubit.userInfoModel);
                    } on DioException catch (e) {
                      if (kDebugMode) {
                        print("Dio Error is: $e");
                      }
                    }
                  },
                  menuPadding: const EdgeInsets.all(16),
                  offset: const Offset(-46, 8),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10)),
                  position: PopupMenuPosition.under,
                  constraints: BoxConstraints(
                      maxWidth: MediaQuery.sizeOf(context).width * 0.7,
                      maxHeight: MediaQuery.sizeOf(context).height * 0.6),
                  itemBuilder: (context) {
                    if (UserInfoCubit.userInfoModel.notifications != null &&
                        UserInfoCubit.userInfoModel.notifications!.isNotEmpty) {
                      return List.generate(
                        (UserInfoCubit.userInfoModel.notifications?.length ??
                            0),
                        (index) {
                          final notif =
                              UserInfoCubit.userInfoModel.notifications![index];
                          return PopupMenuItem(
                              child: Directionality(
                            textDirection: TextDirection.rtl,
                            child: Column(
                              children: [
                                ListTile(
                                  title: Text(
                                    notif.title ?? '',
                                    style: AppTextStyles.body4.copyWith(
                                        fontWeight: FontWeight.bold,
                                        color: Theme.of(context)
                                            .colorScheme
                                            .onSurface),
                                  ),
                                  subtitle: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        notif.message ?? '',
                                        style: AppTextStyles.body4.copyWith(
                                            color: AppColors.gray[context
                                                    .read<ThemeModeCubit>()
                                                    .isDark()
                                                ? 600
                                                : 900]),
                                      ),
                                      const SizedBox(
                                        height: 4,
                                      ),
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.end,
                                        children: [
                                          Text(
                                            '${DateTimeUtils.convertToSentTime(notif.createdAt ?? '')} - ${DateTimeUtils.convertStringIsoToDate(notif.createdAt ?? '').toPersianDateStr()} ',
                                            style: AppTextStyles.body6.copyWith(
                                                color: Theme.of(context)
                                                    .colorScheme
                                                    .primary),
                                          )
                                        ],
                                      )
                                    ],
                                  ),
                                ),
                                if (index !=
                                    UserInfoCubit.userInfoModel.notifications!
                                            .length -
                                        1)
                                  const Divider()
                              ],
                            ),
                          ));
                        },
                      );
                    }
                    return [
                      PopupMenuItem(
                          child: EmptyStates.getEmptyState(
                              status: EmptyStatesEnum.inbox,
                              title: 'صندوق رویدادها خالی است',
                              style: AppTextStyles.body4
                                  .copyWith(fontWeight: FontWeight.bold)))
                    ];
                  },
                  child: Stack(
                    children: [
                      Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: CircleIconBtn(
                            size: Responsive(context).isMobile() ? 32 : 46,
                            iconPadding: Responsive(context).isMobile()
                                ? null
                                : const EdgeInsets.all(8),
                            icon: Assets.icon.outline.notificationBing,
                            color: context.read<ThemeModeCubit>().isDark()
                                ? AppColors.black[900]
                                : AppColors.primaryColor[50],
                            iconColor: Theme.of(context).colorScheme.primary,
                          )),
                      if (UserInfoCubit.userInfoModel.notifications != null &&
                          UserInfoCubit.userInfoModel.notifications!.isNotEmpty)
                        Positioned(
                            top: 0,
                            right: 0,
                            child: BlocBuilder<UserInfoCubit, UserInfoState>(
                                builder: (context, state) {
                              try {
                                final notSeen =
                                    UserInfoCubit.userInfoModel.notifications!
                                        .where(
                                          (e) => e.seen == false,
                                        )
                                        .toList();
                                if (notSeen.isEmpty) {
                                  return const SizedBox.shrink();
                                }

                                return Container(
                                  decoration: BoxDecoration(
                                      shape: BoxShape.circle,
                                      color: AppColors.red.defaultShade),
                                  child: Padding(
                                    padding: const EdgeInsets.all(6),
                                    child: Text(
                                      notSeen.length.toString(),
                                      style: AppTextStyles.body6.copyWith(
                                          color: Colors.white,
                                          fontWeight: FontWeight.bold),
                                    ),
                                  ),
                                )
                                    .animate(
                                      autoPlay: true,
                                      onPlay: (controller) =>
                                          controller.repeat(reverse: true),
                                    )
                                    .scale(
                                      begin: const Offset(1, 1),
                                      end: const Offset(1.2, 1.2),
                                      duration: 600.ms,
                                      curve: Curves.easeInOut,
                                    );
                              } catch (e) {
                                return const SizedBox.shrink();
                              }
                            }))
                    ],
                  ),
                ),
              ],
            ),
          ),
          Flexible(
            flex: 1,
            child: GestureDetector(
              onTap: () => context.go(Routes.myAccount),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  CircleIconBtn(
                    size: Responsive(context).isMobile() ? 32 : 46,
                    iconPadding: Responsive(context).isMobile()
                        ? null
                        : const EdgeInsets.all(8),
                    icon: Assets.icon.outline.coin,
                    color: context.read<ThemeModeCubit>().isDark()
                        ? AppColors.black[900]
                        : AppColors.secondryColor[50],
                    iconColor: Theme.of(context).colorScheme.secondary,
                  )
                      .animate(
                        autoPlay: true,
                        onPlay: (controller) =>
                            controller.repeat(reverse: true),
                      )
                      .moveY(
                          begin: 0,
                          end: -15,
                          duration: 800.ms,
                          curve: Curves.easeInBack,
                          delay: 30.seconds)
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Size get preferredSize => Size.fromHeight(
      kToolbarHeight + (Responsive(context).isMobile() ? 12 : 32));
}
