import 'dart:async';

import 'package:flutter/material.dart';
import '../../product/extention/context_extention.dart';
import '../../product/services/language_services.dart';
import '../../product/constant/enums/app_theme_enums.dart';
import 'bell_bloc.dart';
import '../../product/base/bloc/base_bloc.dart';
import '../../product/services/api_services.dart';
import 'bell_model.dart';

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

  @override
  State<BellScreen> createState() => _BellScreenState();
}

class _BellScreenState extends State<BellScreen> {
  late BellBloc bellBloc;
  APIServices apiServices = APIServices();
  Timer? getBellTimer;
  int offset = 0;
  Bell bell = Bell();
  List<BellItems> items = [];
  bool check = true;
  bool hasMore = true;
  final controller = ScrollController();

  @override
  void initState() {
    super.initState();
    bellBloc = BlocProvider.of(context);
    getBellNotification(offset);
    controller.addListener(
      () {
        if (controller.position.maxScrollExtent == controller.offset) {
          offset += 20;
          getBellNotification(offset);
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<bool>(
      stream: bellBloc.streamIsLoading,
      builder: (context, isLoadingSnapshot) {
        return Scaffold(
          appBar: AppBar(
            title: Text(appLocalization(context).bell_page_title),
            centerTitle: true,
          ),
          body: StreamBuilder<List<BellItems>>(
            stream: bellBloc.streamBellItems,
            initialData: items,
            builder: (context, bellSnapshot) {
              return check
                  ? Center(
                      child: CircularProgressIndicator(
                        value: context.highValue,
                      ),
                    )
                  : bellSnapshot.data?.isEmpty ?? true
                      ? Center(
                          child: Text(
                              appLocalization(context).bell_page_no_items_body),
                        )
                      : SizedBox(
                          width: double.infinity,
                          height: double.infinity,
                          child: RefreshIndicator(
                            onRefresh: refresh,
                            child: ListView.builder(
                              controller: controller,
                              itemCount: (bellSnapshot.data!.length + 1),
                              itemBuilder: (context, index) {
                                if (index < bellSnapshot.data!.length) {
                                  return GestureDetector(
                                    onTap: () async {
                                      List<String> read = [];
                                      read.add(bellSnapshot.data![index].id!);
                                      int code = await apiServices
                                          .updateStatusOfNotification(read);
                                      if (code == 200) {
                                        read.clear();
                                      } else {
                                        read.clear();
                                      }
                                      refresh();
                                    },
                                    child: Column(
                                      children: [
                                        ListTile(
                                          title: Text(
                                            getBellEvent(
                                              context,
                                              bellSnapshot.data![index]
                                                  .itemDetail!.sourceName!,
                                              bellSnapshot
                                                  .data![index].eventType!,
                                              bellSnapshot.data![index]
                                                  .itemDetail!.targetName!,
                                            ),
                                            overflow: TextOverflow.ellipsis,
                                            maxLines: 3,
                                            style:
                                                const TextStyle(fontSize: 15),
                                          ),
                                          trailing: Text(
                                            timeAgo(
                                              context,
                                              bellSnapshot
                                                  .data![index].createdAt!,
                                            ),
                                          ),
                                        ),
                                        const Divider(
                                          height: 1,
                                        ),
                                      ],
                                    ),
                                  );
                                } else {
                                  return Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: StreamBuilder<bool>(
                                      stream: bellBloc.streamHasMore,
                                      builder: (context, hasMoreSnapshot) {
                                        return Center(
                                          child: hasMoreSnapshot.data ?? hasMore
                                              ? const CircularProgressIndicator()
                                              : Text(
                                                  appLocalization(context)
                                                      .bell_read_all,
                                                ),
                                        );
                                      },
                                    ),
                                  );
                                }
                              },
                            ),
                          ),
                        );
            },
          ),
        );
      },
    );
  }

  Future<void> refresh() async {
    check = true;
    offset = 0;
    items.clear();
    bellBloc.sinkBellItems.add(items);
    hasMore = true;
    getBellNotification(offset);
  }

  Future<void> getBellNotification(int offset) async {
    bell = await apiServices.getBellNotifications(
        offset.toString(), (offset + 20).toString());

    if (bell.items!.isEmpty) {
      hasMore = false;
      bellBloc.sinkHasMore.add(hasMore);
    } else {
      for (var item in bell.items!) {
        items.add(item);
      }
    }
    bellBloc.bellItems.add(items);
    check = false;
  }

  bool checkStatus(List<BellItems> bells) {
    for (var bell in bells) {
      if (bell.status == 0) {
        return false;
      }
    }
    return true;
  }

  Future<Color> colorByTheme(int status) async {
    String theme = await apiServices.checkTheme();
    if (theme == AppThemes.LIGHT.name && status == 1) {
      return Colors.white;
    } else if (theme == AppThemes.DARK.name && status == 1) {
      return Colors.black;
    } else {
      return const Color.fromARGB(255, 90, 175, 214);
    }
  }

  String timeAgo(BuildContext context, DateTime dateTime) {
    final duration = DateTime.now().difference(dateTime);

    if (duration.inDays > 0) {
      return '${duration.inDays} ${appLocalization(context).bell_days_ago}';
    } else if (duration.inHours > 0) {
      return '${duration.inHours} ${appLocalization(context).bell_hours_ago}';
    } else if (duration.inMinutes > 0) {
      return '${duration.inMinutes} ${appLocalization(context).bell_minutes_ago}';
    } else {
      return appLocalization(context).bell_just_now;
    }
  }

  String getBellEvent(BuildContext context, String deviceName, String eventCode,
      String targetName) {
    String message = "";

    if (eventCode == "001") {
      message =
          "${appLocalization(context).device_title} $deviceName ${appLocalization(context).disconnect_message_lowercase}";
    } else if (eventCode == "002") {
      message =
          "${appLocalization(context).device_title} $deviceName ${appLocalization(context).gf_connected_lowercase}";
    } else if (eventCode == "003") {
      message =
          "${appLocalization(context).device_title} $deviceName ${appLocalization(context).smoke_detecting_message_lowercase}";
    } else if (eventCode == "004") {
      message =
          "${appLocalization(context).device_title} $deviceName ${appLocalization(context).error_message_lowercase}";
    } else if (eventCode == "005") {
      message =
          "${appLocalization(context).device_title} $deviceName ${appLocalization(context).bell_operate_normal}";
    } else if (eventCode == "006") {
      message =
          "${appLocalization(context).bell_battery_device} $deviceName ${appLocalization(context).low_message_lowercase}";
    } else if (eventCode == "101") {
      message =
          "${appLocalization(context).bell_user_uppercase} ${appLocalization(context).bell_user_joined_group}";
    } else if (eventCode == "102") {
      message =
          "${appLocalization(context).bell_user_uppercase} $deviceName ${appLocalization(context).bell_leave_group} $targetName ";
    } else if (eventCode == "103") {
      message =
          "${appLocalization(context).device_title} $deviceName ${appLocalization(context).bell_user_added_group} $targetName";
    } else if (eventCode == "104") {
      message =
          "${appLocalization(context).device_title} $deviceName ${appLocalization(context).bell_user_kick_group} $targetName";
    } else {
      message = appLocalization(context).bell_invalid_code;
    }

    return message;
  }
}
