import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';
import 'package:road24_mobile/model/utils/styles/AppColors.dart';
import 'package:road24_mobile/data/response/CarsResponse.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/mycar/add/add_new_car_first_step.dart';
import 'package:road24_mobile/view/mycar/add/inspection/widgets/custom_bottom_sheet.dart';
import 'package:road24_mobile/view/widgets/fade_route.dart';
import 'package:road24_mobile/view/widgets/no_connection_screen.dart';
import '../../../my_app.dart';
import 'bloc/cars_list_bloc.dart';
import 'widgets/widgets.dart';
import '../car_details_page.dart';

class CarsListPage extends StatefulWidget {
  final List<Results?> fullList;

  const CarsListPage({Key? key, required this.fullList}) : super(key: key);

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

class _CarsListPageState extends State<CarsListPage>
    with AutomaticKeepAliveClientMixin
    implements CarDetailsImp {
  late var bloc = CarsListBloc(context);
  final int carLIMIT = 50;
  final listKEY = PageStorageKey<String>('controllerA');

  @override
  void initState() {
    bloc.add(CarsChangedListEvent(fullList: widget.fullList, context: context));
    super.initState();
  }

  @override
  void dispose() {
    bloc.close();
    carList.clear();

    super.dispose();
  }

  Future<void> onRefresh() async {
    bloc.add(CarsRefreshEvent());
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<bool>(
        valueListenable: MyApp.hasInternet,
        builder: (_, value, __) {
          if (value) return _widgetHasInternet();
          return _widgetNoInternet();
        });
  }

  var carList = [];
  Widget _widgetHasInternet() {
    return BlocBuilder(
      bloc: bloc,
      builder: (context, state) {
        if (state is CarRefreshSuccessState) {
          carList.clear();
          carList.addAll(state.carList);
        }
        return Scaffold(
            bottomSheet: carList.length < carLIMIT
                ? CustomBottomSheet(
                    onTap: () {
                      Navigator.push(
                        context,
                        CupertinoPageRoute(
                          builder: (_) => AddNewCarFirstStep(),
                          // builder: (_) => AddNewCarOrEditPage(),
                        ),
                      ).then((value) => onRefresh());
                    },
                    buttonColor: Colors.black,
                    title: '${S.of(context).add_car}',
                  )
                : const SizedBox(),
            backgroundColor: AppColors.appPrimaryColor,
            appBar: CarsAppBar(
              title: S.of(context).all_car + " (${carList.length})",
              hintText: S.of(context).search,
            ),
            body: ModalProgressHUD(
              inAsyncCall: state is CarLoadingState,
              child: RefreshIndicator(
                onRefresh: onRefresh,
                child: Scrollbar(
                  isAlwaysShown: true,
                  thickness: 6,
                  child: ListView.builder(
                      key: listKEY,
                      padding: const EdgeInsets.only(bottom: 80),
                      itemCount:
                          carList.length < carLIMIT ? carList.length : carLIMIT,
                      shrinkWrap: true,
                      itemBuilder: (context, index) {
                        final carDetails = carList[index];
                        return Padding(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 8,
                          ),
                          child: CarsListItem(
                            carDetails: carDetails,
                            isPinned: carList.length >= 5,
                            onTapItem: () {
                              Navigator.push(
                                context,
                                CupertinoPageRoute(
                                  builder: (context) => CarDetailsPage(
                                    carDetails: carList[index]!,
                                    imp: this,
                                  ),
                                ),
                              ).then((value) {
                                print("coming to car list page");
                                onRefresh();
                              });
                            },
                            onTapPinned: () {
                              bloc.add(CarsPinnedEvent(
                                context: context,
                                carId: carDetails!.id,
                                pinned: !carDetails.pinned,
                              ));
                            },
                          ),
                        );
                        // }
                      }),
                ),
              ),
            ));
      },
    );
  }

  Widget _widgetNoInternet() {
    return NoConnectionScreen(
      onTap: () {
        Navigator.pushReplacement(
          context,
          FadeRoute(page: CarsListPage(fullList: widget.fullList)),
        );
      },
    );
  }

  @override
  void onChangedCarList(List<Results> fullList) {
    bloc.add(CarsChangedListEvent(fullList: fullList, context: context));
  }

  @override
  bool get wantKeepAlive => true;
}
