import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:road24_mobile/data/repository/CarsRepository.dart';
import 'package:road24_mobile/data/repository/UserRepository.dart';
import 'package:road24_mobile/data/response/CarsResponse.dart';
import 'package:road24_mobile/model/blocs/mycar/cars_bloc.dart';
import 'package:road24_mobile/model/blocs/user/user_bloc.dart';
import 'package:road24_mobile/model/utils/styles/AppColors.dart';
import 'package:road24_mobile/model/utils/styles/AppStyles.dart';
import 'package:road24_mobile/utils/frequent_widgets.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/home/dash_board.dart';
import 'package:road24_mobile/view/shimmer/my_avto_shimmer.dart';
import 'package:road24_mobile/view/widgets/add_new_page.dart';
import 'package:road24_mobile/view/widgets/car_details.dart';
import 'package:road24_mobile/view/widgets/fade_route.dart';
import 'package:road24_mobile/view/widgets/items/cars_list_item.dart';
import 'package:road24_mobile/view/widgets/no_connection_screen.dart';
import 'package:road24_mobile/my_app.dart';
import 'package:sizer/sizer.dart';
import 'add/add_new_car_first_step.dart';
import 'add/add_new_car_or_edit_page.dart';
import 'cars_list/cars_list_page.dart';

class MyCarPage extends StatefulWidget {
  const MyCarPage({Key? key}) : super(key: key);
  static int? current;
  static int? currentId;
  static String? currentCarNumber;

  // ignore: close_sinks
  static ValueNotifier<bool> needToRefresh = ValueNotifier(false);
  static bool carPageNotifierDisposed = false;

  static void onTapCarList(BuildContext context) {
    _MyCarPageState.onTapCarList(context);
  }

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

class _MyCarPageState extends State<MyCarPage> with WidgetsBindingObserver {
  static const int carLIMIT = 5;
  static List<Results?> list = [];
  static List<Results?> newList = [];
  late ValueNotifier<bool?> notificationsEnabled = ValueNotifier(null);
  final _controller = ScrollController();
  static var carsBloc = CarsBloc(repository: CarsRepository());

  var isUserCanAddCar = true;
  var _userBloc = UserBloc(repository: UserRepository());

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    Permission.notification.isGranted.then((value) {
      notificationsEnabled.value = value;
    });
  }

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

    Permission.notification.isGranted.then((value) {
      notificationsEnabled.value = value;
    });
    MyCarPage.needToRefresh = ValueNotifier(false)
      ..addListener(() {
        print("here in car page");
        if (MyCarPage.needToRefresh.value) {
          MyCarPage.needToRefresh.value = false;
          carsBloc.add(GetCars());
        }
      });

    WidgetsBinding.instance?.addObserver(this);
    onRefresh();
  }

  @override
  void dispose() {
    _controller.dispose();
    _userBloc.close();
    notificationsEnabled.dispose();
    WidgetsBinding.instance?.removeObserver(this);
    // carsBloc.close();
    MyCarPage.current = null;
    list.clear();
    newList.clear();
    super.dispose();
  }

  String humanizeCost(String sum) {
    if (sum.endsWith('.0')) {
      sum = sum + '0';
    }
    List<String> sumBuffer = sum.split('.');
    String refactoredSumFormat =
        FrequentWidgets.intComma(int.parse(sumBuffer[0])).replaceAll(',', ' ') +
            '.' +
            sumBuffer[1].toString();
    refactoredSumFormat = refactoredSumFormat.replaceAll(".00", "");
    return refactoredSumFormat;
  }

  static Future<void> onRefresh() async {
    carsBloc.add(GetCars());
    list.clear();
    newList.clear();
  }

  static void onTapCarList(BuildContext context) async {
    await Navigator.push(
      context,
      CupertinoPageRoute(builder: (_) => CarsListPage(fullList: list)),
    );
    onRefresh();
  }

  @override
  Widget build(BuildContext context) {
    // chooseLocation();

    return ValueListenableBuilder<bool>(
        valueListenable: MyApp.hasInternet,
        builder: (context, bool hasInternet, _) {
          if (hasInternet)
            return BlocListener(
              bloc: _userBloc,
              listener: (context, state) {
                // if (state is NoLocationFound) {
                //   chooseLocation();
                // }
              },
              child: BlocBuilder(
                bloc: carsBloc,
                builder: (context, state) {
                  if (state is CarsInitial) return const MyAvtoShimmer();
                  if (state is CarListSuccessState) {
                    print("SUCCESS");
                    list.clear();
                    list.addAll(state.response.results);

                    // print(list);

                    newList.clear();

                    if (list.length > carLIMIT) {
                      newList.addAll(
                          list.where((e) => e?.pinned == true).toList());

                      if (newList.length < carLIMIT) {
                        var someList = list
                            .where(
                                (element) => element != null && !element.pinned)
                            .toList()
                            .sublist(0, carLIMIT - newList.length);

                        newList.addAll(someList);
                      }
                    } else {
                      newList.addAll(list);

                      newList.sort((a, b) => (b != null && b.pinned) ? 1 : -1);
                    }
                    // if (!MyApp.preferences!.getFirstOpen()) {
                    //   MyApp.preferences?.setFirstOpen2(false).then((value) {
                    //     MyApp.preferences?.setFirstOpen(true).then((value) {
                    //       WidgetsBinding.instance?.addPostFrameCallback(
                    //           (_) => ShowCaseWidget.of(context)?.startShowCase([
                    //                 DashBoard.key1,
                    //               ]));
                    //     });
                    //   });
                    // }
                    if (MyCarPage.current == null && newList.isNotEmpty) {
                      MyCarPage.current = 0;
                      MyCarPage.currentId = newList[MyCarPage.current!]?.id;
                      MyCarPage.currentCarNumber = newList[0]?.number;
                    }
                    // else if (MyCarPage.current != null &&
                    //     newList[MyCarPage.current!]?.id != MyCarPage.currentId) {
                    //   print("there are not equal");
                    //   MyCarPage.current = 0;
                    //   MyCarPage.currentId = newList[MyCarPage.current!]?.id;
                    //   MyCarPage.currentCarNumber = newList[0]?.number;
                    // }
                  }

                  return Builder(builder: (context) {
                    if (list.isNotEmpty) {
                      return Stack(
                        children: [
                          Container(
                            height: 92.0.h - 6.0.w,
                            child: RefreshIndicator(
                              color: Colors.grey,
                              onRefresh: onRefresh,
                              child: ListView(
                                  controller: _controller,
                                  shrinkWrap: true,
                                  children: [
                                    Column(
                                      children: [
                                        const SizedBox(height: 6.0),
                                        widgetCars(),
                                        widgetProgress(),
                                        ValueListenableBuilder(
                                            valueListenable:
                                                notificationsEnabled,
                                            builder:
                                                (context, bool? isEnabled, _) {
                                              if (isEnabled != null &&
                                                  isEnabled)
                                                return const SizedBox();
                                              else
                                                return const EnableNotification();
                                            }),
                                        CarDetails(
                                          carDetails: MyCarPage.current! >=
                                                  newList.length
                                              ? null
                                              : newList[MyCarPage.current!],
                                        ),
                                        const SizedBox(height: 20.0)
                                      ],
                                    ),
                                  ]),
                            ),
                          ),
                        ],
                      );
                    } else {
                      return AddNewPage(
                        text: "${S.of(context).lets_add_car}",
                        subText: "${S.of(context).you_need_car_number}",
                        btnText: "${S.of(context).add_car}",
                        onTap: () async {
                          Navigator.push(
                            context,
                            CupertinoPageRoute(
                              builder: (_) => AddNewCarFirstStep(),
                            ),
                          );
                        },
                      );
                    }
                  });
                },
              ),
            );
          else
            return NoConnectionScreen(
              onTap: () {
                Navigator.pushReplacement(
                  context,
                  FadeRoute(page: const DashBoard()),
                );
              },
            );
        });
  }

  Widget widgetCars() {
    if (list.length >= 50) {
      isUserCanAddCar = false;
    }

    var carItemLengths = 0;

    if (newList.length > carLIMIT) {
      carItemLengths = carLIMIT;
    } else {
      carItemLengths = newList.length;
    }
    return CarouselSlider(
      items: List.generate(
          isUserCanAddCar ? carItemLengths + 1 : carItemLengths, (index) {
        if (index < carItemLengths) {
          return CarsListItem(
            carDetails: newList[index]!,
            onTapEdit: () {
              Navigator.push(
                context,
                CupertinoPageRoute(
                  builder: (_) => AddNewCarOrEditPage(
                    carDetails: newList[index],
                    isFromMain: true,
                  ),
                ),
              );
            },
          );
        } else if (isUserCanAddCar)
          return GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              Navigator.push(
                context,
                CupertinoPageRoute(
                  builder: (_) => AddNewCarFirstStep(),
                  // builder: (_) => AddNewCarOrEditPage(),
                ),
              );
            },
            child: Container(
              height: 250.0,
              width: 320.0,
              margin: const EdgeInsets.symmetric(horizontal: 3.0),
              alignment: Alignment.center,
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: (MyCarPage.current == index)
                    ? Colors.white
                    : Color(0xFFFAFAFA),
                borderRadius: BorderRadius.circular(12.0),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    S.of(context).add_car,
                    style: AppStyle.textStyle().copyWith(
                      color: AppColors.selectedColor,
                      fontSize: 18,
                    ),
                  ),
                  const SizedBox(height: 5),
                  const Icon(
                    CupertinoIcons.add_circled,
                    color: AppColors.selectedColor,
                    size: 30,
                  ),
                ],
              ),
            ),
          );

        return const SizedBox();
      }),
      options: CarouselOptions(
        enableInfiniteScroll: false,
        initialPage: MyCarPage.current != null ? MyCarPage.current! : 0,
        enlargeCenterPage: true,
        disableCenter: true,
        onPageChanged: (index, reason) {
          print("carousel slide action");
          setState(
            () {
              MyCarPage.current = index;
              if (MyCarPage.current! < newList.length) {
                MyCarPage.currentId = newList[MyCarPage.current!]?.id;
                MyCarPage.currentCarNumber =
                    newList[MyCarPage.current!]?.number;
              }
            },
          );
        },
      ),
    );
  }

  Widget widgetProgress() {
    var carItemLengths = 0;

    if (newList.length > carLIMIT) {
      carItemLengths = carLIMIT;
      // if (isUserCanAddCar) carItemLengths++;
    } else {
      carItemLengths = newList.length;
    }
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 4.0.w),
      child: Row(
        children: List.generate(
          isUserCanAddCar ? carItemLengths + 1 : carItemLengths,
          (index) => Expanded(
            child: Container(
              height: 0.5.w,
              margin: EdgeInsets.symmetric(vertical: 2.0.h, horizontal: 3.0),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(0.5.w),
                color: MyCarPage.current == index
                    ? Color(0xFF282828)
                    : Color(0xFFC4C4C4),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class EnableNotification extends StatelessWidget {
  const EnableNotification({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.max,
          children: [
            const SizedBox(width: 16.0),
            Expanded(
              child: GestureDetector(
                onTap: () {
                  openAppSettings();
                },
                child: Container(
                  height: 70.0,
                  padding: const EdgeInsets.all(6.0),
                  decoration: BoxDecoration(
                    color: AppColors.color333333,
                    borderRadius: BorderRadius.circular(12.0),
                    border: Border.all(
                      color: AppColors.color333333,
                    ),
                  ),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Expanded(
                        flex: 1,
                        child: Container(
                          padding: const EdgeInsets.all(6.0),
                          decoration: BoxDecoration(
                            color: Color(0xffE9E9E9),
                            shape: BoxShape.circle,
                          ),
                          child: const Icon(Icons.notifications_off_outlined,
                              color: AppColors.error),
                          margin: const EdgeInsets.symmetric(vertical: 6.0),
                        ),
                      ),
                      Expanded(
                        flex: 5,
                        child: Text(
                          S.of(context).turn_on_notification,
                          style: AppStyle.textStyle().copyWith(
                            color: Colors.white,
                            fontSize: 15.0,
                            fontWeight: FontWeight.w400,
                          ),
                          maxLines: 2,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            const SizedBox(width: 16.0),
          ],
        ),
        const SizedBox(height: 11.0),
      ],
    );
  }
}
