import 'dart:async';
import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/dashboard_latest/dashboard_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/enums/user_types.dart';
import 'package:test_sa/models/new_models/dashboard_detail.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/new_views/pages/land_page/requests/request_paginated_listview.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';

class RequestsListPage extends StatefulWidget {
  static const String routeName = "/requests-list-page";
  final int index;
  final String title;

  const RequestsListPage(this.index, this.title, {Key? key}) : super(key: key);

  @override
  State<RequestsListPage> createState() => _RequestsListPageState();
}

class _RequestsListPageState extends State<RequestsListPage> {
  // late AllRequestsProvider _provider;
  late DashBoardProvider _dashBoardProvider;
  late ScrollController _scrollController;

  @override
  void initState() {
    super.initState();
    _dashBoardProvider = Provider.of<DashBoardProvider>(context, listen: false);
    scheduleMicrotask(() async {
      _dashBoardProvider.resetRequestDataList();
      callRequestApis();
    });
    handleScroll();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void handleScroll() async {
    _scrollController = ScrollController();
    int pageNo = 1;
    _scrollController.addListener(() async {
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent &&
          !_dashBoardProvider.isDetailLoading &&
          (_dashBoardProvider.requestDetailList!.data!.length < _dashBoardProvider.requestDetailList!.totalRows!.toInt())) {
        log('I am here in scroll ');
        pageNo = pageNo + 1;
        _dashBoardProvider.pageNum = pageNo;
        callRequestApis(showLoader: false, pageNo: pageNo);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: DefaultAppBar(title: "${widget.title} ${context.translation.requests}"),
        body: SafeArea(
          child: Consumer<DashBoardProvider>(builder: (context, snapshot, _) {
            if (snapshot.isDetailLoading || snapshot.requestDetailList == null) {
              return ListView.builder(
                itemCount: 6,
                padding: const EdgeInsets.all(16),
                itemBuilder: (context, index) {
                  return Padding(
                    padding: EdgeInsets.symmetric(vertical: 10.toScreenHeight, horizontal: 0),
                    child: const SizedBox().toRequestShimmer(context, snapshot.isDetailLoading),
                  );
                },
              );
            } else if (snapshot.requestDetailList?.data?.isEmpty ?? true) {
              return const NoDataFound().center;
            } else {
              return RequestPaginatedListview(snapshot.requestDetailList?.data ?? <Data>[], snapshot.isDetailLoading, snapshot.requestDetailList?.totalRows ?? 0, _scrollController);
            }
            // bool isLoading = widget.index == 0
            //     ? snapshot.isHighPriorityLoading
            //     : widget.index == 1
            //         ? snapshot.isOverdueLoading
            //         : widget.index == 2
            //             ? snapshot.isOpenLoading
            //             : widget.index == 3
            //                 ? snapshot.isCompleteLoading
            //                 : false;
            //
            // List<RequestsDetails> list = widget.index == 0
            //     ? snapshot.highPriorityRequests?.requestsDetails ?? []
            //     : widget.index == 1
            //         ? snapshot.overdueRequests?.requestsDetails ?? []
            //         : widget.index == 2
            //             ? snapshot.openRequests?.requestsDetails ?? []
            //             : widget.index == 3
            //                 ? snapshot.completedRequests?.requestsDetails ?? []
            //                 : [];
          }),
        ));
  }

  Future<void> callRequestApis({bool showLoader = true, int pageNo = 1, int pageSize = 10}) async {
    UsersTypes usersTypes = Provider.of<UserProvider>(context, listen: false).user!.type!;
    if (widget.index == 0) {
      // high priority

      _dashBoardProvider.getHighPriorityRequests(usersType: usersTypes, showLoader: showLoader);
    } else if (widget.index == 1) {
      // overdue
      _dashBoardProvider.getOverdueRequests(usersType: usersTypes, showLoader: showLoader);
    } else if (widget.index == 2) {
      //in progress
      _dashBoardProvider.getInProgressRequests(usersType: usersTypes, showLoader: showLoader);
    } else {
      // completed
      _dashBoardProvider.getCompletedRequests(usersType: usersTypes, showLoader: showLoader);
    }
  }
}
