import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:road24_mobile/data/repository/FinesRepository.dart';
import 'package:road24_mobile/data/response/FinesResponse.dart';
import 'package:road24_mobile/model/blocs/fines/fines_bloc.dart';
import 'package:road24_mobile/model/utils/styles/AppColors.dart';
import 'package:road24_mobile/model/utils/styles/AppStyles.dart';
import 'package:road24_mobile/my_app.dart';
import 'package:road24_mobile/utils/frequent_widgets.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/shimmer/fines_shimmer.dart';
import 'package:road24_mobile/view/widgets/fade_route.dart';
import 'package:road24_mobile/view/widgets/no_connection_screen.dart';
import 'package:road24_mobile/view/widgets/items/fines_list_item.dart';
import 'package:road24_mobile/view/widgets/items/car_number.dart';
import 'package:sizer/sizer.dart';
import '../my_car_page.dart';
import 'fine_details_empty.dart';
import 'fine_details_page.dart';

class FinesPage extends StatefulWidget {
  const FinesPage({Key? key}) : super(key: key);
  static bool isRefreshed = false;

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

class _FinesPageState extends State<FinesPage>
    with SingleTickerProviderStateMixin {
  late TabController controller;
  int _activeTab = 0;

  final ScrollController notPaidScrollController = ScrollController();
  final ScrollController historyScrollController = ScrollController();
  final FinesBloc _bloc = FinesBloc(repository: FinesRepository());

  int notPaidPageNumber = 1;
  int historyPageNumber = 1;
  int? notPaidCount;
  int? historyCount;
  bool loading = false;
  ValueNotifier<bool> takingNextForNotPaid = ValueNotifier(true);
  ValueNotifier<bool> takingNextForHistory = ValueNotifier(true);
  List<Results> notPaid = [];
  List<Results> history = [];

  @override
  void dispose() {
    _bloc.close();
    takingNextForNotPaid.dispose();
    takingNextForHistory.dispose();
    notPaidScrollController.dispose();
    historyScrollController.dispose();
    notPaid.clear();
    history.clear();
    controller.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    loading = true;
    controller = TabController(initialIndex: 0, length: 2, vsync: this);
    controller
      ..addListener(() => setState(() => _activeTab = controller.index));
    onRefresh();
    notPaidScrollController.addListener(_notPaidScrollListener);
    historyScrollController.addListener(_historyScrollListener);
  }

  void initialize() {
    _bloc.add(GetFines(
      pageNumber: notPaidPageNumber,
      pageSize: 10,
      types: [1, 3],
      carId: MyCarPage.currentId!,
    ));
    _bloc.add(GetFines(
      pageNumber: historyPageNumber,
      pageSize: 10,
      types: [2, 4, 5],
      carId: MyCarPage.currentId!,
    ));
  }

  Future<void> onRefresh() async {
    FinesPage.isRefreshed = false;
    notPaidCount = null;
    historyCount = null;
    notPaidPageNumber = 1;
    historyPageNumber = 1;
    notPaid.clear();
    history.clear();

    initialize();
  }

  void _notPaidScrollListener() {
    try {
      if (notPaidScrollController.position != null) {
        if (notPaidScrollController.position.pixels ==
            notPaidScrollController.position.maxScrollExtent) {
          notPaidPageNumber++;
          if (notPaidCount != null) {
            if (notPaidCount! > notPaid.length) {
              _bloc.add(
                GetFines(
                  pageNumber: notPaidPageNumber,
                  pageSize: 10,
                  types: [1, 3],
                  carId: MyCarPage.currentId!,
                ),
              );
            } else {
              takingNextForNotPaid.value = false;
            }
          } else {
            _bloc.add(
              GetFines(
                pageNumber: notPaidPageNumber,
                pageSize: 10,
                types: [1, 3],
                carId: MyCarPage.currentId!,
              ),
            );
          }
        }
      }
    } catch (e) {
      print(e.toString());
    }
  }

  void _historyScrollListener() {
    try {
      if (historyScrollController.position != null) {
        if (historyScrollController.position.pixels ==
            historyScrollController.position.maxScrollExtent) {
          if (historyCount != null) {
            if (historyCount! > history.length) {
              _bloc.add(
                GetFines(
                  pageNumber: historyPageNumber,
                  pageSize: 10,
                  types: [2, 4, 5],
                  carId: MyCarPage.currentId!,
                ),
              );
            } else {
              takingNextForHistory.value = false;
            }
          } else {
            _bloc.add(
              GetFines(
                pageNumber: historyPageNumber,
                pageSize: 10,
                types: [2, 4, 5],
                carId: MyCarPage.currentId!,
              ),
            );
          }
          historyPageNumber++;
        }
      }
    } catch (e) {
      print(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      valueListenable: MyApp.hasInternet,
      builder: (context, bool hasInternet, _) {
        return (hasInternet)
            ? BlocConsumer(
                bloc: _bloc,
                listener: (context, state) {
                  if (state is NotPaidFinesListSuccessState) {
                    if (loading) {
                      setState(() {
                        loading = false;
                      });
                    }
                    if (notPaidCount == null) {
                      notPaidCount = state.response.count;
                    }
                    for (var fine in state.response.results!) {
                      notPaid.add(fine);
                    }
                    if (notPaidCount == 0 || notPaidCount == notPaid.length) {
                      takingNextForNotPaid.value = false;
                    }
                  } else if (state is HistoryFinesListSuccessState) {
                    setState(() {
                      loading = false;
                    });
                    if (historyCount == null) {
                      historyCount = state.response.count;
                    }
                    try {
                      for (var fine in state.response.results!) {
                        history.add(fine);
                      }
                      if (historyCount == 0 || historyCount == history.length) {
                        takingNextForHistory.value = false;
                      }
                    } catch (ex) {
                      print("exceppppptptptp: $ex");
                    }
                  }
                },
                builder: (context, state) {
                  if (state is FinesInitial &&
                      (notPaidCount == null || historyCount == null)) {
                    return const FinesShimmer();
                  } else if (state is FinesFail) {
                    return const FineDetailsEmpty();
                  }
                  return Scaffold(
                    backgroundColor: AppColors.appPrimaryColor,
                    body: Container(
                      margin: const EdgeInsets.symmetric(horizontal: 15.0),
                      width: 100.0.w,
                      child: SafeArea(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            const SizedBox(height: 8.0),
                            InkWell(
                              onTap: () {
                                Navigator.pop(context);
                              },
                              child: Container(
                                  decoration: BoxDecoration(
                                    color: Color(0xffDFDFDF),
                                    shape: BoxShape.circle,
                                  ),
                                  padding: const EdgeInsets.all(8),
                                  child: Icon(
                                    Icons.arrow_back_ios_outlined,
                                    size: 20.0,
                                    color: Colors.black,
                                  )),
                            ),
                            const SizedBox(height: 8.0),
                            Row(
                              children: [
                                Expanded(
                                  flex: 3,
                                  child: Text(
                                    "${S.of(context).fines}",
                                    style: AppStyle.textStyle().copyWith(
                                        color: Color(0xff282828),
                                        fontWeight: FontWeight.w700,
                                        fontSize: 24.0),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                                CarNumber(
                                    carNumber: MyCarPage.currentCarNumber!,
                                    fontSize: 18.0),
                              ],
                            ),
                            const SizedBox(height: 16.0),
                            Container(
                              height: 50.0,
                              padding:
                                  const EdgeInsets.symmetric(vertical: 5.0),
                              decoration: BoxDecoration(
                                color:
                                    const Color(0xff767680).withOpacity(0.12),
                                borderRadius: BorderRadius.circular(100.0),
                              ),
                              child: TabBar(
                                isScrollable: false,
                                controller: controller,
                                indicatorColor: Colors.transparent,
                                labelPadding:
                                    const EdgeInsets.symmetric(horizontal: 0.0),
                                tabs: <Widget>[
                                  FrequentWidgets.createTabForMain(
                                      "${S.of(context).not_paid} ${(notPaidCount != null) ? "($notPaidCount)" : ""}",
                                      _activeTab == 0),
                                  FrequentWidgets.createTabForMain(
                                      "${S.of(context).history} ${(historyCount != null) ? "($historyCount)" : ""}",
                                      _activeTab == 1),
                                ],
                              ),
                            ),
                            Expanded(
                              child: Container(
                                child: (notPaidCount == 0 &&
                                        historyCount ==
                                            0) //perhaps new user (Empty state)
                                    ? emptyState()
                                    : TabBarView(
                                        physics:
                                            const NeverScrollableScrollPhysics(),
                                        controller: controller,
                                        children: <Widget>[
                                          (notPaidCount != null &&
                                                  notPaidCount == 0 &&
                                                  historyCount! >
                                                      0) //all fines are paid (Paid state)
                                              ? allPaidState()
                                              : RefreshIndicator(
                                                  color: Colors.grey,
                                                  onRefresh: onRefresh,
                                                  child: ListView.builder(
                                                    shrinkWrap: true,
                                                    physics:
                                                        const AlwaysScrollableScrollPhysics(),
                                                    controller:
                                                        notPaidScrollController,
                                                    itemCount:
                                                        notPaid.length + 1,
                                                    itemBuilder:
                                                        (context, index) {
                                                      if (index ==
                                                          notPaid.length) {
                                                        return ValueListenableBuilder(
                                                          valueListenable:
                                                              takingNextForNotPaid,
                                                          builder: (context,
                                                              bool isTaking,
                                                              _) {
                                                            if (isTaking &&
                                                                !loading) {
                                                              return const Center(
                                                                child:
                                                                    CircularProgressIndicator(
                                                                  strokeWidth:
                                                                      3.0,
                                                                  valueColor:
                                                                      AlwaysStoppedAnimation<
                                                                          Color>(
                                                                    AppColors
                                                                        .unSelectedColor,
                                                                  ),
                                                                ),
                                                              );
                                                            } else {
                                                              return const SizedBox();
                                                            }
                                                          },
                                                        );
                                                      } else {
                                                        return FinesListItem(
                                                          // number: index,
                                                          result:
                                                              notPaid[index],
                                                          onTap: () {
                                                            Navigator.push(
                                                              context,
                                                              CupertinoPageRoute(
                                                                builder:
                                                                    (context) {
                                                                  return FineDetailsPage(
                                                                    id: notPaid[
                                                                            index]
                                                                        .id!,
                                                                  );
                                                                },
                                                              ),
                                                            ).then((value) {
                                                              if (FinesPage
                                                                  .isRefreshed) {
                                                                onRefresh();
                                                              }
                                                            });
                                                          },
                                                        );
                                                      }
                                                    },
                                                  ),
                                                ),
                                          ((notPaidCount != null &&
                                                      historyCount != null) &&
                                                  (notPaidCount! > 0 &&
                                                      historyCount ==
                                                          0)) //perhaps new user (Empty state)
                                              ? noSinglePaidState()
                                              : RefreshIndicator(
                                                  color: Colors.grey,
                                                  onRefresh: onRefresh,
                                                  child: ListView.builder(
                                                    physics:
                                                        const AlwaysScrollableScrollPhysics(),
                                                    controller:
                                                        historyScrollController,
                                                    itemCount:
                                                        history.length + 1,
                                                    itemBuilder:
                                                        (context, index) {
                                                      if (index ==
                                                          history.length) {
                                                        return ValueListenableBuilder(
                                                          valueListenable:
                                                              takingNextForHistory,
                                                          builder: (context,
                                                              bool isTaking,
                                                              _) {
                                                            if (isTaking &&
                                                                !loading) {
                                                              return const Center(
                                                                child:
                                                                    CircularProgressIndicator(
                                                                  strokeWidth:
                                                                      3.0,
                                                                  valueColor:
                                                                      AlwaysStoppedAnimation<
                                                                          Color>(
                                                                    AppColors
                                                                        .unSelectedColor,
                                                                  ),
                                                                ),
                                                              );
                                                            } else {
                                                              return const SizedBox();
                                                            }
                                                          },
                                                        );
                                                      } else {
                                                        return FinesListItem(
                                                          // number: index,
                                                          result:
                                                              history[index],
                                                          onTap: () {
                                                            Navigator.push(
                                                              context,
                                                              CupertinoPageRoute(
                                                                builder:
                                                                    (context) {
                                                                  return FineDetailsPage(
                                                                    id: history[
                                                                            index]
                                                                        .id!,
                                                                  );
                                                                },
                                                              ),
                                                            );
                                                          },
                                                        );
                                                      }
                                                    },
                                                  ),
                                                ),
                                        ],
                                      ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                },
              )
            : NoConnectionScreen(
                onTap: () {
                  Navigator.pushReplacement(
                    context,
                    FadeRoute(page: const FinesPage()),
                  );
                },
              );
      },
    );
  }

  Widget emptyState() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 15.0),
        child: RefreshIndicator(
          color: Colors.grey,
          onRefresh: onRefresh,
          child: SingleChildScrollView(
            physics: AlwaysScrollableScrollPhysics(),
            child: Container(
              height: 100.0.h - 170,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisSize: MainAxisSize.max,
                children: [
                  const Text(
                    '😄',
                    style: TextStyle(fontSize: 60.0),
                  ),
                  const SizedBox(height: 15.0),
                  Text(
                    S.of(context).empty_state_title,
                    textAlign: TextAlign.center,
                    style: AppStyle.textStyle().copyWith(
                      color: Colors.black,
                      fontSize: 24.0,
                      fontWeight: FontWeight.w700,
                    ),
                    maxLines: 1,
                  ),
                  const SizedBox(height: 5.0),
                  Text(
                    S.of(context).empty_state_body,
                    style: AppStyle.textStyle().copyWith(
                      color: Color(0xff282828),
                      fontSize: 15.0,
                      fontWeight: FontWeight.w600,
                    ),
                    textAlign: TextAlign.center,
                    maxLines: 3,
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget allPaidState() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 15.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const Text(
            '😊',
            style: TextStyle(fontSize: 60.0),
          ),
          const SizedBox(height: 15.0),
          Text(
            S.of(context).all_paid_state_title,
            textAlign: TextAlign.center,
            style: AppStyle.textStyle().copyWith(
              color: Colors.black,
              fontSize: 24.0,
              fontWeight: FontWeight.w700,
            ),
            maxLines: 1,
          ),
          const SizedBox(height: 5.0),
          Text(
            S.of(context).all_paid_state_body,
            style: AppStyle.textStyle().copyWith(
              color: Color(0xff282828),
              fontSize: 15.0,
              fontWeight: FontWeight.w600,
            ),
            textAlign: TextAlign.center,
            maxLines: 3,
          ),
        ],
      ),
    );
  }

  Widget noSinglePaidState() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 15.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.max,
        children: [
          const Text(
            '🙄',
            style: TextStyle(fontSize: 60.0),
          ),
          const SizedBox(height: 15.0),
          Text(
            S.of(context).no_single_paid_state_title,
            textAlign: TextAlign.center,
            style: AppStyle.textStyle().copyWith(
              color: Colors.black,
              fontSize: 24.0,
              fontWeight: FontWeight.w700,
            ),
            maxLines: 1,
          ),
          const SizedBox(height: 5.0),
          Text(
            S.of(context).no_single_paid_state_body,
            style: AppStyle.textStyle().copyWith(
              color: Color(0xff282828),
              fontSize: 15.0,
              fontWeight: FontWeight.w600,
            ),
            textAlign: TextAlign.center,
            maxLines: 3,
          ),
        ],
      ),
    );
  }
}
