import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:initial_folder/base_service.dart';
import 'package:initial_folder/models/notification.dart';
import 'package:initial_folder/providers/detail_course_provider.dart';
import 'package:initial_folder/providers/lesson_course_provider.dart';
import 'package:initial_folder/providers/notification_provider.dart';
import 'package:initial_folder/screens/course/play_course_page.dart';
import 'package:initial_folder/services/course_service.dart';
import 'package:initial_folder/services/lesson_course_service.dart';
import 'package:initial_folder/services/notification_service.dart';
import 'package:initial_folder/size_config.dart';
import 'package:initial_folder/theme.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:shimmer/shimmer.dart';

class Notifikasi extends StatelessWidget {
  const Notifikasi({Key? key}) : super(key: key);
  static String routeName = "/notifikasi";

  initNotif(BuildContext context) async {
    FirebaseMessaging.onMessage.listen((event) async {
      if (event.data.isNotEmpty) {
        await Provider.of<NotificationProvider>(context, listen: false)
            .getMyNotification();
        await Provider.of<NotificationProvider>(context, listen: false)
            .getNotificationCount();
      }
    });
    Future.delayed(const Duration(seconds: 0), () async {
      await Provider.of<NotificationProvider>(context, listen: false)
          .getMyNotification();
      await Provider.of<NotificationProvider>(context, listen: false)
          .getNotificationCount();
    });
  }

  readAllHandler(
    BuildContext context,
  ) async {
    await Provider.of<NotificationProvider>(context, listen: false)
        .markAsRead();
    if (!context.mounted) return;
    Provider.of<NotificationProvider>(context, listen: false).changeAllRead();
  }

  @override
  Widget build(BuildContext context) {
    final Brightness brightnessValue =
        MediaQuery.of(context).platformBrightness;
    bool isDarkMode = brightnessValue == Brightness.dark;
    initNotif(context);

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.background,
        scrolledUnderElevation: 0.0,
        actions: [
          IconButton(
            tooltip: "Mark as Read",
            onPressed: () => readAllHandler(
              context,
            ),
            icon: const Icon(Icons.drafts),
          ),
        ],
        centerTitle: true,
        title: Text(
          'Notifikasi',
          style: secondaryTextStyle.copyWith(
            letterSpacing: 1,
            fontWeight: semiBold,
            fontSize: getProportionateScreenWidth(14),
          ),
        ),
      ),
      body: RefreshIndicator(
        displacement: 40,
        onRefresh: () async {
          await Provider.of<NotificationProvider>(context, listen: false)
              .getMyNotification();
        },
        child: Consumer<NotificationProvider>(
          builder: (context, value, child) {
            if (value.state == resultState.Loading) {
              return Shimmer.fromColors(
                baseColor: Colors.grey,
                highlightColor: Colors.white,
                child: ListView.builder(
                  itemCount: 6,
                  itemBuilder: (context, index) {
                    return Padding(
                      padding: EdgeInsets.only(
                          bottom: getProportionateScreenHeight(10)),
                      child: Container(
                        width: double.infinity,
                        padding:
                            EdgeInsets.all(getProportionateScreenWidth(10)),
                        decoration: BoxDecoration(
                            color: Colors.white,
                            border: Border(
                                bottom: BorderSide(color: Colors.white))),
                        child: Row(
                          children: [
                            SizedBox(
                              height: getProportionateScreenHeight(50),
                              child: Container(
                                color: Colors.white,
                                width: getProportionateScreenWidth(100),
                              ),
                            ),
                            SizedBox(width: getProportionateScreenWidth(10)),
                            Expanded(
                              flex: 3,
                              child: Column(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceAround,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Container(
                                    color: Colors.white,
                                    height: getProportionateScreenHeight(2),
                                  ),
                                  SizedBox(
                                    height: getProportionateScreenHeight(15),
                                  ),
                                  Container(
                                    color: Colors.white,
                                    height: getProportionateScreenHeight(15),
                                  ),
                                  SizedBox(
                                    height: getProportionateScreenHeight(5),
                                  ),
                                  Container(
                                    color: Colors.white,
                                    height: getProportionateScreenHeight(15),
                                  ),
                                  SizedBox(
                                    height: getProportionateScreenHeight(5),
                                  ),
                                  Container(
                                    color: Colors.white,
                                    height: getProportionateScreenHeight(15),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                ),
              );
            } else if (value.state == resultState.Error) {
              return Center(
                child: ListView(
                  children: [
                    Container(
                      padding: const EdgeInsets.all(20.0),
                      constraints: BoxConstraints(
                          minHeight: MediaQuery.of(context).size.height / 1.5),
                      child: Center(
                        child: Text('Terjadi Kesalahan'),
                      ),
                    )
                  ],
                ),
              );
            } else if (value.state == resultState.NoData) {
              return Center(
                child: ListView(
                  children: [
                    Container(
                      padding: const EdgeInsets.all(20.0),
                      constraints: BoxConstraints(
                          minHeight: MediaQuery.of(context).size.height / 1.5),
                      child: Center(
                        child: Text('Notifikasi Kosong'),
                      ),
                    )
                  ],
                ),
              );
            } else {
              var allResults = [...value.result, ...value.resultAnnouncement];
              return ListView.builder(
                itemCount: allResults.length,
                itemBuilder: (context, index) {
                  return GestureDetector(
                      onTap: () async {
                        Provider.of<NotificationProvider>(context,
                                listen: false)
                            .changeIsRead(value.result, index);
                        await NotificationServices().readNotification(
                            value.result[index].idRead!,
                            value.result[index].ket!);
                        if (!context.mounted) return;
                        Navigator.of(context, rootNavigator: true).push(
                          MaterialPageRoute(
                            builder: (context) => MultiProvider(
                              providers: [
                                ChangeNotifierProvider(
                                  create: (context) => LessonCourseProvider(
                                    lessonCourseService: LessonCourseService(),
                                    id: int.parse(
                                        value.result[index].idCourse ?? '0'),
                                  ),
                                ),
                                ChangeNotifierProvider(
                                  create: (context) => DetailCourseProvider(
                                    courseService: CourseService(),
                                    id: value.result[index].idCourse ?? '1',
                                  ),
                                )
                              ],
                              child: PlayCourse(
                                judul: value.result[index].titleCourse ?? '',
                                instruktur:
                                    value.result[index].instructor ?? '',
                                thumbnail: value.result[index].thumbnail ??
                                    '$baseUrl/uploads/courses_thumbnail/course_thumbnail_default_57.jpg',
                                courseeid: value.result[index].idCourse ?? '',
                                isQna: (value.result[index].subject ==
                                        "Q&A Kursus")
                                    ? true
                                    : false,
                              ),
                            ),
                          ),
                        );
                      },
                      child: Padding(
                        padding: EdgeInsets.fromLTRB(
                            getProportionateScreenWidth(20),
                            getProportionateScreenHeight(5),
                            getProportionateScreenWidth(20),
                            getProportionateScreenHeight(5)),
                        child: Container(
                          width: double.infinity,
                          padding:
                              EdgeInsets.all(getProportionateScreenWidth(10)),
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(10),
                              boxShadow: [
                                BoxShadow(
                                  color:
                                      isDarkMode ? Colors.black : Colors.grey,
                                  spreadRadius: 0.01,
                                  blurRadius: 2,
                                  offset: Offset(0, 1), // Shadow position
                                ),
                              ],
                              color: Theme.of(context)
                                  .colorScheme
                                  .primaryContainer,
                              border: Border(
                                  bottom: BorderSide(color: Colors.white12))),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              SizedBox(
                                  height: getProportionateScreenHeight(60),
                                  child: (value.result[index].thumbnail == "" ||
                                          value.result[index].thumbnail == null)
                                      ? Image.network(
                                          'https://api.vokasia.id/images/default-thumbnail.png',
                                          fit: BoxFit.fill,
                                          width:
                                              getProportionateScreenWidth(120),
                                        )
                                      : Image.network(
                                          value.result[index].thumbnail!,
                                          fit: BoxFit.fill,
                                          width:
                                              getProportionateScreenWidth(120),
                                        )),
                              SizedBox(width: getProportionateScreenWidth(10)),
                              Expanded(
                                flex: 3,
                                child: Column(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceAround,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      value.result[index].subject!,
                                      style: thirdTextStyle.copyWith(
                                        fontSize: 12,
                                        fontWeight: reguler,
                                        color: Theme.of(context)
                                            .colorScheme
                                            .onPrimary,
                                      ),
                                    ),
                                    SizedBox(
                                      height: getProportionateScreenHeight(15),
                                      child: Row(
                                        children: [
                                          Text(
                                            DateFormat('dd MMMM yyyy ').format(
                                              DateTime
                                                  .fromMillisecondsSinceEpoch(
                                                      int.parse(value
                                                              .result[index]
                                                              .timestamps!) *
                                                          1000),
                                            ),
                                            style: thirdTextStyle.copyWith(
                                              fontSize: 12,
                                              fontWeight: reguler,
                                              color: Theme.of(context)
                                                  .colorScheme
                                                  .onPrimary,
                                            ),
                                          ),
                                          Padding(
                                            padding: EdgeInsets.symmetric(
                                                horizontal:
                                                    getProportionateScreenWidth(
                                                        5)),
                                            child: Icon(Icons.lens_rounded,
                                                color: Color(0xffc4c4c4),
                                                size:
                                                    getProportionateScreenWidth(
                                                        7)),
                                          ),
                                          Text(
                                              value.result[index].date!
                                                  .substring(
                                                      value.result[index].date!
                                                              .length -
                                                          8,
                                                      value.result[index].date!
                                                              .length -
                                                          3),
                                              style: thirdTextStyle.copyWith(
                                                fontSize: 12,
                                                fontWeight: reguler,
                                                color: Theme.of(context)
                                                    .colorScheme
                                                    .onPrimary,
                                              )),
                                          SizedBox(
                                              width:
                                                  getProportionateScreenWidth(
                                                      10)),
                                          notificationPing(value.result[index])
                                        ],
                                      ),
                                    ),

                                    RichText(
                                        overflow: TextOverflow.ellipsis,
                                        maxLines: 2,
                                        text: TextSpan(
                                          text: (value.result[index].messages !=
                                                  null)
                                              ? value.result[index].messages!
                                              : "",
                                          style: thirdTextStyle.copyWith(
                                            fontSize: 12,
                                            fontWeight: reguler,
                                            color: Theme.of(context)
                                                .colorScheme
                                                .onPrimary,
                                          ),
                                        )),
                                    // Text(
                                    //   (value.result[index].messages != null)
                                    //       ? value.result[index].messages!
                                    //       : "",
                                    //   style: thirdTextStyle.copyWith(
                                    //     fontSize: 12,
                                    //     fontWeight: reguler,
                                    //     color: Theme.of(context)
                                    //         .colorScheme
                                    //         .onPrimary,
                                    //   ),
                                    // ),
                                    SizedBox(
                                        height:
                                            getProportionateScreenHeight(5)),
                                    RichText(
                                        overflow: TextOverflow.ellipsis,
                                        maxLines: 2,
                                        text: TextSpan(
                                          text:
                                              value.result[index].titleCourse!,
                                          style: thirdTextStyle.copyWith(
                                            fontSize: 12,
                                            fontWeight: reguler,
                                            color: Theme.of(context)
                                                .colorScheme
                                                .onPrimary,
                                          ),
                                        )),
                                    // Text(
                                    //   value.result[index].titleCourse!,
                                    //   style: thirdTextStyle.copyWith(
                                    //       fontSize:
                                    //           getProportionateScreenHeight(10)),
                                    // ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      ));
                },
              );
            }
          },
        ),
      ),
    );
  }

  Widget notificationPing(NotificationData data) {
    if (data.isRead == "0") {
      return Icon(Icons.lens_rounded,
          color: Color(0xffCD2228), size: getProportionateScreenWidth(10));
    } else {
      return SizedBox();
    }
  }
}
