import 'dart:convert';

import 'package:boilerplate/core/di/injection_init.dart';
import 'package:boilerplate/core/enum/notification.dart';
import 'package:boilerplate/core/styles/my_dimensions.dart';
import 'package:boilerplate/core/styles/my_font.dart';
import 'package:boilerplate/core/utils/navigator_util.dart';
import 'package:boilerplate/presentation/screen/web_view/web_view_screen.dart';
import 'package:boilerplate/presentation/widgets/base_scaffold.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_badger/flutter_app_badger.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

import '../../../core/constant/constants.dart';
import '../../../core/utils/shared_preferences_util.dart';
import '../../../domain/entities/flavor/flavor_data.dart';
import '../../bloc/notification/notification_count/notification_count_cubit.dart';
import '../../bloc/notification/notifications/notification_bloc.dart';
import '../../widgets/ipm_data_not_found.dart';

class NotificationsScreen extends StatefulWidget {
  NotificationsScreen({Key? key}) : super(key: key);

  @override
  State<NotificationsScreen> createState() => _NotificationsScreenState();
}

class _NotificationsScreenState extends State<NotificationsScreen> {
  final GlobalKey<RefreshIndicatorState> _refresh =
      GlobalKey<RefreshIndicatorState>();
  late final NotificationsBloc _bloc;
  late String lang = '';
  getLang() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    setState(() {
      lang = prefs.getString('lang').toString();
    });
    await FirebaseAnalytics.instance
        .logScreenView(screenName: 'NotificationPage');
  }

  @override
  void initState() {
    super.initState();

    _bloc = getIt.get<NotificationsBloc>();

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _refresh.currentState?.show();
    });
    getLang();
  }

  Future<bool> _onRefresh() async {
    _bloc..add(GetNotificationsEvent());
    var state = await _bloc.stream.firstWhere((state) =>
        state is GetNotificationsSuccessState ||
        state is GetNotificationsFailState);
    return state is GetNotificationsSuccessState ||
        state is GetNotificationsFailState;
  }

  @override
  void dispose() {
    _bloc.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<NotificationsBloc, NotificationsState>(
      bloc: _bloc,
      builder: (context, state) {
        return BaseScaffold(
          title: lang == "th" || lang == "" ? 'การแจ้งเตือน' : "Notification",
          onBack: true,
          body: Stack(
            children: [
              RefreshIndicator(
                key: _refresh,
                onRefresh: _onRefresh,
                child: ListView.separated(
                  padding: EdgeInsets.all(MyDimens.dimen16).copyWith(
                    bottom: MediaQuery.of(context).padding.bottom +
                        MyDimens.dimen16,
                  ),
                  itemCount: state.data.notifications.length,
                  itemBuilder: (context, index) {
                    final noti = state.data.notifications[index];

                    return GestureDetector(
                      onTap: () async {
                        await encrytion(
                            state.data.notifications[index].id.toString(),
                            state.data.notifications[index].status.toString());
                        final pref = getIt.get<SharedPreferencesUtil>();

                        pref.putInt(
                            SharedPreferencesUtil.keyNotificationCount, 0);

                        FlutterAppBadger.removeBadge();
                        FlutterAppBadger.updateBadgeCount(0);
                        if (NavigatorUtil.navigate.currentState != null) {
                          BlocProvider.of<NotificationCountCubit>(
                                  NavigatorUtil.navigate.currentState!.context)
                              .clearNotificationCount();
                        }
                        FlutterAppBadger.removeBadge();
                        if (noti.type == NotificationType.offerReply) {
                          await NavigatorUtil.pushToPage(
                            WebViewScreen(
                              url:
                                  '${getIt.get<AppFlavorData>().webDomain}/offer/${state.data.notifications[index].id.toString()}&mobile=1&lang=${lang}',
                              title: lang == "th" || lang == ""
                                  ? 'การแจ้งเตือน'
                                  : "Notification",
                            ),
                          );
                        } else {
                          await NavigatorUtil.pushToPage(
                            WebViewScreen(
                              url:
                                  '${getIt.get<AppFlavorData>().webDomain}/me?mobile=1#tabs-2',
                              title: lang == "th" || lang == ""
                                  ? 'การแจ้งเตือน'
                                  : "Notification",
                            ),
                          );
                        }
                        // if (noti.type == "offer_reply") {
                        //   await NavigatorUtil.pushToPage(
                        //     WebViewScreen(
                        //       url:
                        //           // '${getIt.get<AppFlavorData>().webDomain}$WEB_MEET',
                        //           '${getIt.get<AppFlavorData>().webDomain}/me?mobile=1#tabs-3',
                        //       title: lang == "th" || lang == ""
                        //           ? 'การแจ้งเตือน'
                        //           : "Notification",
                        //     ),
                        //   );
                        // } else if (noti.type ==
                        //     NotificationType.sellerConfirmMatching) {
                        // } else if (noti.type == NotificationType.newMatching ||
                        //     noti.type == NotificationType.comingupMatching) {
                        //   await NavigatorUtil.pushToPage(WebViewScreen(
                        //     url:
                        //         '${getIt.get<AppFlavorData>().webDomain}/me?mobile=1#tabs-3',
                        //     // '${getIt.get<AppFlavorData>().webDomain}$WEB_MEET',
                        //     title: lang == "th" || lang == ""
                        //         ? 'การแจ้งเตือน'
                        //         : "Notification",
                        //   ));
                        // } else {}
                      },
                      child: Card(
                        elevation: 3,
                        child: Container(
                          constraints: BoxConstraints(
                            minHeight: MyDimens.dimen80,
                          ),
                          padding: EdgeInsets.symmetric(
                            vertical: MyDimens.dimen10,
                            horizontal: MyDimens.dimen14,
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                noti.title,
                                style: MyFont.medium16,
                              ),
                              SizedBox(height: MyDimens.dimen4),
                              Text(
                                noti.body,
                                style: MyFont.regular14,
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ],
                          ),
                        ),
                      ),
                    );
                  },
                  separatorBuilder: (context, index) => SizedBox(
                    height: MyDimens.dimen12,
                  ),
                ),
              ),
              if ((state is GetNotificationsSuccessState ||
                      state is GetNotificationsFailState) &&
                  state.data.notifications.length == 0)
                IPMDataNotFound(
                  paddingTop: MyDimens.dimen100,
                ),
            ],
          ),
        );
      },
    );
  }

  encrytion(String id, String status) async {
    String url = "https://ipmart.ipthailand.go.th/api/notification/update";
    Object body = {"id": "${id}", "message_status": "${status}"};
    // print(body);
    var response = await http.post(
      Uri.parse(url),
      body: body,
    );
    // print(url);
    // print("encrytion body=> ${body}");
    var res = json.decode(response.body)['data'];
    print("response.body encrytion=> ${response.body}");
    print("================================");
    if (response.statusCode == 200) {
      // decrytion(json.decode(response.body)['data']);
      return res.toString();
      print("200");
    } else {
      // print(loginResult.errorMessage);
    }
  }
}
