import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:road24_mobile/data/repository/ChequeRepository.dart';
import 'package:road24_mobile/data/response/ChequeListResponse.dart';
import 'package:road24_mobile/data/response/FinesResponse.dart';
import 'package:road24_mobile/model/blocs/cheque/cheque_bloc.dart';
import 'package:road24_mobile/model/utils/Config.dart';
import 'package:road24_mobile/model/utils/styles/AppColors.dart';
import 'package:road24_mobile/model/utils/styles/AppStyles.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/shimmer/notification_shimmer.dart';
import 'package:road24_mobile/view/widgets/items/fines_list_item.dart';
import 'package:road24_mobile/utils/extensions.dart';
import 'fines_cheque_details.dart';

class FinesChequeList extends StatefulWidget {
  const FinesChequeList({
    Key? key,
  }) : super(key: key);
  _FinesChequeListState createState() => _FinesChequeListState();
}

class _FinesChequeListState extends State<FinesChequeList>
    with TickerProviderStateMixin {
  var loadingAll = true;
  var loadingRoad = true;
  final ChequeBloc chequeBloc = ChequeBloc(repository: ChequeRepository());

  GlobalKey<ScaffoldState> _key = GlobalKey();
  List<Results> chequeList = [];
  List<ChequeResult> roadChequeList = [];
  int pageNumber = 1;
  int pageSize = 10;

  int pageNumberRoad = 1;
  int pageSizeRoad = 10;

  // late TabController _tabController;
  ScrollController _scrollController = ScrollController();

  ScrollController _scrollControllerForRoad = ScrollController();

  ChequeListResponse? response;
  AllChequeListResponse? responseForRoad;

  bool isPaginating = false;
  ValueNotifier<bool> isPaginatingRoad = ValueNotifier(false);

  int _activeTab = 0;

  @override
  void dispose() {
    _scrollController.dispose();
    _scrollControllerForRoad.dispose();
    chequeBloc.close();
    isPaginatingRoad.dispose();
    super.dispose();
  }

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

    // _tabController = TabController(length: 2, vsync: this);

    // _tabController
    //   ..addListener(() => setState(() => _activeTab = _tabController.index));

    // apiRequest(pageNumber);

    // _scrollController.addListener(_listenerForAll);
    isPaginatingRoad.value = true;

    apiRequestForRoad(pageNumberRoad);

    _scrollControllerForRoad.addListener(_listenerForRoad);
  }

  apiRequest(int page) {
    setState(() {
      isPaginating = true;
    });

    chequeBloc.add(GetChequeList(page: page, pageSize: pageSize));
  }

  apiRequestForRoad(int page) {
    chequeBloc.add(GetAllChequeList(page: page, pageSize: pageSizeRoad));
  }

  void _listenerForAll() {
    try {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        if (response != null && response!.next != null) {
          pageNumber++;
          apiRequest(pageNumber);
        }
      }
    } catch (e) {
      print("scroll exception $e");
    }
  }

  void _listenerForRoad() {
    try {
      if (_scrollControllerForRoad.position.pixels ==
          _scrollControllerForRoad.position.maxScrollExtent) {
        if (responseForRoad != null && responseForRoad!.next != null) {
          pageNumberRoad++;
          apiRequestForRoad(pageNumberRoad);
        }
      }
    } catch (e) {
      print("scroll exception 2 $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener(
        bloc: chequeBloc,
        listener: (context, state) {
          print(state.toString());
          if (state is ChequeListSuccessState) {
            if (state.response is AllChequeListResponse) {
              setState(() {
                responseForRoad = state.response;
                roadChequeList.addAll(state.response.results);
                loadingRoad = false;

                if (responseForRoad != null && responseForRoad!.next == null)
                  isPaginatingRoad.value = false;
              });
            } else {
              setState(() {
                response = state.response;
                chequeList.addAll(state.response.results);
                loadingAll = false;
                isPaginating = false;
              });
            }
          } else if (state is ChequeErrorState) {
            setState(() {
              loadingRoad = false;
              loadingAll = false;
              isPaginating = false;
              isPaginatingRoad.value = false;
            });

            String? text;
            try {
              text = state.exception.toString().getErrorText();
            } catch (ex) {
              text = state.exception.toString() + "";
            }

            Config.showSnackBar(
              context,
              text,
            );
          }
        },
        child:
            // DefaultTabController(
            //   length: 2,
            //   child: Column(
            //     children: [
            // Container(
            //   height: 50.0,
            //   alignment: Alignment.center,
            //   width: double.infinity,
            //   padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 4),
            //   margin: EdgeInsets.symmetric(horizontal: 16.0),
            //   decoration: BoxDecoration(
            //     color: Color(0xff767680).withOpacity(0.12),
            //     borderRadius: BorderRadius.circular(100.0),
            //   ),
            //   child: TabBar(
            //     // isScrollable: false,
            //     controller: _tabController,
            //     indicatorColor: Colors.transparent,
            //     labelPadding: EdgeInsets.symmetric(horizontal: 0.0),
            //     // indicator: BoxDecoration(
            //     //   borderRadius: BorderRadius.circular(100),
            //     //   color: Colors.white,
            //     // ),
            //     tabs: <Widget>[
            //       FrequentWidgets.createTabForMain(
            //           S.of(context).byRoad24, _activeTab == 0),
            //       FrequentWidgets.createTabForMain(
            //           S.of(context).allPayments, _activeTab == 1)
            //     ],
            //   ),
            // ),
            // Expanded(
            //   child: TabBarView(
            //       controller: _tabController,
            //       physics: NeverScrollableScrollPhysics(),
            //       children: [
            Scaffold(
          key: _key,
          backgroundColor: AppColors.appPrimaryColor,
          body: road24ChequeList(),
        )
        //   chequeListTab(),
        // ]),
        //     ),
        //   ],
        // ),
        // ),
        );
  }

  road24ChequeList() {
    return RefreshIndicator(
      onRefresh: () async {
        setState(() {
          loadingRoad = true;
        });
        roadChequeList.clear();

        pageNumberRoad = 1;
        apiRequestForRoad(pageNumberRoad);
      },
      child: loadingRoad
          ? Center(child: NotificationShimmer())
          : SingleChildScrollView(
              controller: _scrollControllerForRoad,
              child: Column(
                children: [
                  roadChequeList.length == 0
                      ? noCheque()
                      : ListView.builder(
                          shrinkWrap: true,
                          padding: const EdgeInsets.symmetric(horizontal: 16.0),
                          physics: NeverScrollableScrollPhysics(),
                          itemCount: roadChequeList.length,
                          itemBuilder: (context, index) {
                            var item = roadChequeList[index];
                            var result = Results(
                                id: item.id,
                                pSeryNumber: item.fine!.pSeryNumber ?? "",
                                pLocation: "",
                                pViolation: item.fine?.pViolation!,
                                pDate: item.createdDate,
                                pStatus: 1,
                                remain: "0.00",
                                checkId: item.id,
                                parentId: item.fine?.id,
                                pAmount: item.amount.toString());
                            return FinesListItem(
                              isHistory: true,
                              isRoad: true,
                              result: result,
                              onTap: () {
                                Navigator.push(
                                  context,
                                  CupertinoPageRoute(
                                    builder: (context) {
                                      return FinesChequeDetails(
                                        results: result,
                                      );
                                    },
                                  ),
                                );
                              },
                            );
                          }),
                  SizedBox(
                    height: 10,
                  ),
                  ValueListenableBuilder(
                      valueListenable: isPaginatingRoad,
                      builder: (context, bool isPaginating, _) {
                        if (isPaginating)
                          return Center(
                            child: CircularProgressIndicator(
                              strokeWidth: 3.0,
                              valueColor: AlwaysStoppedAnimation<Color>(
                                AppColors.unSelectedColor,
                              ),
                            ),
                          );
                        return Container();
                      }),
                  SizedBox(
                    height: 20,
                  )
                ],
              ),
            ),
    );
  }

  chequeListTab() {
    return Container(
      child: RefreshIndicator(
        onRefresh: () async {
          loadingAll = true;
          chequeList.clear();
          pageNumber = 1;
          apiRequest(pageNumber);
        },
        child: loadingAll
            ? Center(child: NotificationShimmer())
            : ListView.builder(
                controller: _scrollController,
                shrinkWrap: true,
                padding: const EdgeInsets.symmetric(horizontal: 16.0),
                physics: AlwaysScrollableScrollPhysics(),
                itemCount: chequeList.length + 1,
                itemBuilder: (context, index) {
                  if (chequeList.length == 0) {
                    return noCheque();
                  } else if (chequeList.length == index) {
                    if (isPaginating) return CupertinoActivityIndicator();

                    return SizedBox();
                  } else {
                    var item = chequeList[index];
                    item.pPlace = item.pSeryNumber;
                    return FinesListItem(
                      isHistory: true,
                      result: item,
                      onTap: () {
                        Navigator.push(
                          context,
                          CupertinoPageRoute(
                            builder: (context) {
                              return FinesChequeDetails(
                                results: item,
                              );
                            },
                          ),
                        );
                      },
                    );
                  }
                }),
      ),
    );
  }

  Widget noCheque() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(height: MediaQuery.of(context).size.height * 0.22),
          Text(
            '😄',
            style: TextStyle(fontSize: 50.0),
          ),
          SizedBox(height: 15.0),
          Text(
            S.of(context).no_cheque_title,
            textAlign: TextAlign.center,
            style: AppStyle.textStyle().copyWith(
              color: Colors.black,
              fontSize: 24.0,
              fontWeight: FontWeight.w700,
            ),
            maxLines: 1,
          ),
          SizedBox(height: 5.0),
          Text(
            S.of(context).no_cheque_body,
            style: AppStyle.textStyle().copyWith(
              color: Color(0xff282828),
              fontSize: 15.0,
              fontWeight: FontWeight.w600,
            ),
            textAlign: TextAlign.center,
            maxLines: 3,
          ),
        ],
      ),
    );
  }
}
