import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:road24_mobile/data/repository/NotificationsRepository.dart';
import 'package:road24_mobile/data/response/NotificationsResponse.dart';
import 'package:road24_mobile/model/blocs/notifications/notifications_bloc.dart';
import 'package:road24_mobile/model/utils/styles/AppColors.dart';
import 'package:road24_mobile/model/utils/styles/AppStyles.dart';
import 'package:road24_mobile/utils/frequent_widgets.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/home/dash_board.dart';
import 'package:road24_mobile/view/mycar/add/add_new_car_first_step.dart';
import 'package:road24_mobile/view/mycar/add/confident_page.dart';
import 'package:road24_mobile/view/mycar/add/inspection/inspection_page.dart';
import 'package:road24_mobile/view/mycar/add/insurance_page.dart';
import 'package:road24_mobile/view/mycar/add/oil_page_new.dart';
import 'package:road24_mobile/view/mycar/add/tinting_page.dart';
import 'package:road24_mobile/view/mycar/fines/fine_details_page.dart';
import 'package:road24_mobile/view/shimmer/notification_shimmer.dart';
import 'package:road24_mobile/view/widgets/items/new_notification_Item.dart';
import 'package:sizer/sizer.dart';
import 'package:url_launcher/url_launcher.dart';

import 'markdown_page.dart';

class NotificationScreen extends StatefulWidget {
  static List<Results> notifications = [];
  static int? notificationsCount;
  static int pageNumber = 1;

  @override
  _NotificationsState createState() => _NotificationsState();
}

class _NotificationsState extends State<NotificationScreen> {
  var _scrollController = ScrollController();
  var takingNext = ValueNotifier(true);
  final listViewKey = PageStorageKey(0);

  @override
  void initState() {
    if (NotificationScreen.notifications.isEmpty) {
      NotificationScreen.notificationsCount = null;
    }
    _loadData();
    super.initState();
  }

  @override
  void dispose() {
    print("notification disposed");
    NotificationScreen.notifications.clear();
    NotificationScreen.pageNumber = 1;
    _scrollController.dispose();
    takingNext.dispose();
    super.dispose();
  }

  _loadData() {
    NotificationScreen.notifications.clear();
    DashBoard.notificationsBloc.add(
      GetNotificationsEvent(
        page: NotificationScreen.pageNumber,
        pageSize: 10,
      ),
    );
    _scrollController.addListener(_listener);
  }

  void _listener() {
    try {
      if (_scrollController.position != null) {
        if (_scrollController.position.pixels ==
            _scrollController.position.maxScrollExtent) {
          NotificationScreen.pageNumber++;
          if (NotificationScreen.notificationsCount != null) {
            if (NotificationScreen.notificationsCount! >
                NotificationScreen.notifications.length) {
              DashBoard.notificationsBloc.add(
                GetNotificationsEvent(
                  page: NotificationScreen.pageNumber,
                  pageSize: 10,
                ),
              );
            } else {
              takingNext.value = false;
            }
          } else {
            DashBoard.notificationsBloc.add(
              GetNotificationsEvent(
                page: NotificationScreen.pageNumber,
                pageSize: 10,
              ),
            );
          }
        }
      }
    } catch (e) {
      print(e.toString());
    }
  }

  Future<void> _onRefresh() async {
    NotificationScreen.pageNumber = 1;
    NotificationScreen.notifications.clear();
    NotificationScreen.notificationsCount = null;
    DashBoard.notificationsBloc.add(GetNotificationsEvent(
      page: NotificationScreen.pageNumber,
      pageSize: 10,
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.appPrimaryColor,
      appBar: AppBar(
        toolbarHeight: 60.0,
        leading: FrequentWidgets.appBarBackButton(context),
        title: Text(
          S.of(context).notifications,
          style: AppStyle.textStyle().copyWith(
              color: Colors.black, fontWeight: FontWeight.w600, fontSize: 21.0),
        ),
      ),
      body: BlocListener(
        bloc: DashBoard.notificationsBloc,
        listener: (context, state) {
          if (state is GetNotificationsSuccessState) {
            if (NotificationScreen.notificationsCount == null) {
              NotificationScreen.notificationsCount = state.response.count;
            }
            if (NotificationScreen.notificationsCount! >
                NotificationScreen.notifications.length) {
              for (var notification in state.response.results ?? []) {
                print(notification.notificationContent.action);
                NotificationScreen.notifications.add(notification);
              }
            }
            if (NotificationScreen.notificationsCount ==
                NotificationScreen.notifications.length) {
              takingNext.value = false;
            }
          }
        },
        child: BlocBuilder(
          bloc: DashBoard.notificationsBloc,
          builder: (context, state) {
            if (state is NotificationsInitial &&
                NotificationScreen.notificationsCount == null) {
              return Center(child: NotificationShimmer());
            }
            if (state is GetNotificationsSuccessState) {
              if (state.response.results!.isEmpty) {
                return RefreshIndicator(
                  color: Colors.grey,
                  onRefresh: _onRefresh,
                  child: SingleChildScrollView(
                    physics: AlwaysScrollableScrollPhysics(),
                    child: Container(
                      constraints: BoxConstraints(minHeight: 80.0.h),
                      padding: const EdgeInsets.symmetric(horizontal: 16.0),
                      child: Center(
                        child: Text(
                          S.of(context).no_notification,
                          style: AppStyle.textStyle().copyWith(
                              color: Color(0xff282828),
                              fontSize: 24.0,
                              fontWeight: FontWeight.w600),
                          maxLines: 2,
                        ),
                      ),
                    ),
                  ),
                );
              }
            }
            print(NotificationScreen.notifications.length);
            return RefreshIndicator(
              color: Colors.grey,
              onRefresh: _onRefresh,
              child: SingleChildScrollView(
                key: listViewKey,
                controller: _scrollController,
                physics: AlwaysScrollableScrollPhysics(),
                child: Container(
                  constraints: BoxConstraints(
                    minHeight: 92.0.h - 6.0.w,
                  ),
                  child: Column(
                    children: [
                      ...List.generate(NotificationScreen.notifications.length,
                          (index) {
                        String? difference;
                        if (NotificationScreen
                                .notifications[index].createdDate !=
                            null) {
                          difference =
                              FrequentWidgets.calculateTimeDifferenceBetween(
                                  context,
                                  startDateStr: NotificationScreen
                                      .notifications[index].createdDate!,
                                  endDate: DateTime.now());
                        }
                        var svgIconName = getIconPath(NotificationScreen
                            .notifications[index].notificationContent!.action);

                        return InkWell(
                          onTap: () async {
                            print("notification action: " +
                                NotificationScreen.notifications[index]
                                    .notificationContent!.action
                                    .toString());
                            if (!NotificationScreen
                                .notifications[index].isRead) {
                              print("not read");
                              NotificationRepository()
                                  .userReadNotification(NotificationScreen
                                      .notifications[index].id!)
                                  .then((value) {
                                setState(() {
                                  NotificationScreen
                                      .notifications[index].isRead = true;
                                });
                                DashBoard.notificationCount.value--;
                              });
                            }
                            onTapAction(NotificationScreen
                                .notifications[index].notificationContent);
                            // _onRefresh();
                          },
                          child: NotificationItemNew(
                            date: difference,
                            svgIconName: svgIconName,
                            notification:
                                NotificationScreen.notifications[index],
                          ),
                        );
                      }),
                      SizedBox(height: 10.0),
                      ValueListenableBuilder(
                        valueListenable: takingNext,
                        builder: (context, bool isTaking, _) {
                          if (isTaking &&
                              NotificationScreen.notificationsCount != null) {
                            return Center(
                              child: CircularProgressIndicator(
                                strokeWidth: 3.0,
                                valueColor: AlwaysStoppedAnimation<Color>(
                                  AppColors.unSelectedColor,
                                ),
                              ),
                            );
                          } else
                            return SizedBox();
                        },
                      ),
                      SizedBox(height: 20.0),
                    ],
                  ),
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  String getIconPath(NotificationType? action) {
    switch (action) {
      case NotificationType.PARTIAL_PAID_FINE:

      case NotificationType.COMPLETELY_PAID_FINE:
      case NotificationType.NEW_FINE:
      case NotificationType.PAY_FINE_SUCCESS:
      case NotificationType.PAY_FINE_FAILED:
      case NotificationType.FINE_IMAGES_FOUND:
        return "fine_icon";
      case NotificationType.FINE_DISCOUNT_ENDING:
        return "sale";

      case NotificationType.OIL:
        return "oil_notification";

      case NotificationType.WEATHER_STATUS:
        return "cloudy";

      case NotificationType.ROAD_BLOCK:
        return "roadblock";

      case NotificationType.TRUST:
        return "trust";

      case NotificationType.TINTING:
        return "tonirovka";

      case NotificationType.LEGAL_NEWS:
        return "scales";

      case NotificationType.BIG_NEWS:
        return "news";

      // case NotificationType.TEST_EXERCISE:
      //   return "tests";

      case NotificationType.ADD_CAR:
        return "car_add";

      case NotificationType.CAR_INSURANCE:
        return "car_insurance";

      case NotificationType.INSPECTION_COMING_END:
        return "texosmotr";

      case NotificationType.INSPECTION_COMING_END:
        return "stores";
      default:
        return "news";
    }
  }

  onTapAction(NotificationContent? notificationContent) {
    if (notificationContent != null && notificationContent.action != null)
      switch (notificationContent.action) {
        case NotificationType.PARTIAL_PAID_FINE:

        case NotificationType.COMPLETELY_PAID_FINE:
        case NotificationType.NEW_FINE:
        case NotificationType.PAY_FINE_SUCCESS:
        case NotificationType.PAY_FINE_FAILED:
        case NotificationType.FINE_IMAGES_FOUND:
        case NotificationType.FINE_DISCOUNT_ENDING:
          Navigator.push(
            context,
            CupertinoPageRoute(
              builder: (context) => FineDetailsPage(
                id: notificationContent.content!.data!.objId!,
              ),
            ),
          );
          break;
        case NotificationType.OIL:
          Navigator.push(
            context,
            CupertinoPageRoute(builder: (context) => OilPage()),
          );
          break;
        // return "oil_notification";
        case NotificationType.WEATHER_STATUS:
          if (notificationContent.id != null)
            Navigator.push(
              context,
              CupertinoPageRoute(
                  builder: (context) => NotificationDetails(
                        title: notificationContent.content?.title ??
                            "Weather status",
                        id: notificationContent.id!,
                      )),
            );
          break;
        case NotificationType.ROAD_BLOCK:
          if (notificationContent.id != null)
            Navigator.push(
              context,
              CupertinoPageRoute(
                  builder: (context) => NotificationDetails(
                        title:
                            notificationContent.content?.title ?? "Road Block",
                        id: notificationContent.id!,
                      )),
            );
          break;
        case NotificationType.TRUST:
          Navigator.push(
            context,
            CupertinoPageRoute(
              builder: (context) => ConfidentPage(),
            ),
          );
          break;
        case NotificationType.CAR_INSURANCE:
          Navigator.push(
            context,
            CupertinoPageRoute(
              builder: (context) => InsurancePage(),
            ),
          );
          break;
        case NotificationType.TINTING:
          Navigator.push(
            context,
            CupertinoPageRoute(
              builder: (context) => TintingPage(),
            ),
          );
          break;
        case NotificationType.LEGAL_NEWS:
          if (notificationContent.id != null)
            Navigator.push(
              context,
              CupertinoPageRoute(
                  builder: (context) => NotificationDetails(
                        title:
                            notificationContent.content?.title ?? "Legal News",
                        id: notificationContent.id!,
                      )),
            );
          break;
        case NotificationType.BIG_NEWS:
          if (notificationContent.id != null)
            Navigator.push(
              context,
              CupertinoPageRoute(
                  builder: (context) => NotificationDetails(
                        title: notificationContent.content?.title ?? "Big News",
                        id: notificationContent.id!,
                      )),
            );
          break;
        case NotificationType.TEST_EXERCISE:
          print("here in test");
          var url = notificationContent.content?.data?.targetUrl;
          print("url ...$url");
          if (url != null) launch(url);
          // Navigator.push(
          //   context,
          //   CupertinoPageRoute(
          //       builder: (context) => NotificationDetails(
          //             title:
          //                 notificationContent.content?.title ?? "Test Exercise",
          //           )),
          // );
          break;

        case NotificationType.REPORT_REVIEWED:
          break;
        case NotificationType.OFFENCE_CHANGED_STATUS:
          break;

        case NotificationType.ADD_CAR:
          Navigator.push(
            context,
            CupertinoPageRoute(builder: (context) => AddNewCarFirstStep()),
          );
          break;

        case NotificationType.INSPECTION_COMING_END:
          var carDetailId = notificationContent.content!.data!.carDetailId;

          if (carDetailId != null)
            Navigator.push(
              context,
              CupertinoPageRoute(
                builder: (context) => InspectionPage(
                  carId: carDetailId,
                ),
              ),
            );
          break;

        case NotificationType.STORES:
          var url = notificationContent.content?.data?.androidUrl;

          if (Platform.isIOS) {
            url = notificationContent.content?.data?.iosUrl;
          }
          print("url ...$url");
          if (url != null) launch(url);
          break;

        case null:
          break;
      }
  }
}
