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/data/repository/CardRepository.dart';
import 'package:road24_mobile/data/response/GetCardResponse.dart';
import 'package:road24_mobile/model/blocs/card/card_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/view/built/i18n.dart';
import 'package:road24_mobile/view/mycar/add/inspection/widgets/custom_bottom_sheet.dart';
import 'package:road24_mobile/view/settings/card/add/add_card_page.dart';
import 'package:road24_mobile/view/widgets/add_new_page.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/card_item.dart';
import 'package:sizer/sizer.dart';

class CardsPage extends StatefulWidget {
  static List<Gradient> gradients = [
    LinearGradient(colors: [
      Color(0xFF2f4759),
      Color(0xFF479fac),
    ], begin: Alignment.bottomLeft, end: Alignment.topRight),
    LinearGradient(colors: [
      Color(0xFF01adc2),
      Color(0xFF85e6f6),
    ], begin: Alignment.bottomLeft, end: Alignment.topRight),
    LinearGradient(colors: [
      Color(0xFFffac06),
      Color(0xFFfedd00),
    ], begin: Alignment.bottomLeft, end: Alignment.topRight),
    LinearGradient(colors: [
      Color(0xFF9cbee1),
      Color(0xFFbbe7f8),
    ], begin: Alignment.bottomLeft, end: Alignment.topRight),
    LinearGradient(colors: [
      Color(0xFF217ace),
      Color(0xFF1fbbf6),
    ], begin: Alignment.bottomLeft, end: Alignment.topRight),
    // LinearGradient(colors: [
    //   Color(0xFF992b34),
    //   Color(0xFF9c2832),
    // ], begin: Alignment.bottomLeft, end: Alignment.topRight),
    LinearGradient(colors: [
      Color(0xFF7160e1),
      Color(0xFFd562c3),
    ], begin: Alignment.bottomLeft, end: Alignment.topRight),
    LinearGradient(colors: [
      Color(0xFF123075),
      Color(0xFF4490ef),
    ], begin: Alignment.bottomLeft, end: Alignment.topRight),
    LinearGradient(colors: [
      Color(0xFF3bd5a6),
      Color(0xFFb0ecb0),
    ], begin: Alignment.bottomLeft, end: Alignment.topRight),
  ];

  static List<CardResults> cards = [];

  // ignore: close_sinks
  static CardBloc cardBloc = CardBloc(repository: CardRepository());
  static ValueNotifier<bool> loading = ValueNotifier(true);
  static ValueNotifier<bool> needToRefresh = ValueNotifier(false)
    ..addListener(() async {
      if (CardsPage.needToRefresh.value) {
        CardsPage.needToRefresh.value = false;

        CardsPage.cardBloc.add(GetCardsEvent());
      }
    });

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

class _CardsPageState extends State<CardsPage> {
  // GetCardsResponse response;

  @override
  void initState() {
    CardsPage.cardBloc.add(GetCardsEvent());
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    CardsPage.needToRefresh.value = false;
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
        valueListenable: MyApp.hasInternet,
        builder: (context, bool hasInternet, _) {
          return (hasInternet)
              ? ValueListenableBuilder(
                  valueListenable: CardsPage.loading,
                  builder: (context, bool loading, _) => ModalProgressHUD(
                    inAsyncCall: loading,
                    color: AppColors.unSelectedColor,
                    progressIndicator: CircularProgressIndicator(
                      strokeWidth: 3.0,
                      valueColor: AlwaysStoppedAnimation<Color>(
                        AppColors.unSelectedColor,
                      ),
                    ),
                    child: Scaffold(
                      bottomSheet: CardsPage.cards.length == 0
                          ? SizedBox()
                          : CustomBottomSheet(
                              onTap: () {
                                Navigator.push(
                                  context,
                                  CupertinoPageRoute(
                                    builder: (context) => AddCardPage(),
                                  ),
                                );
                              },
                              buttonColor: AppColors.color333333,
                              title: '${S.of(context).add_card}',
                            ),
                      backgroundColor: AppColors.appPrimaryColor,
                      appBar: AppBar(
                        toolbarHeight: 60.0,
                        leading: Material(
                          type: MaterialType.transparency,
                          child: InkWell(
                            onTap: () {
                              Navigator.pop(context);
                            },
                            child: Container(
                              margin: EdgeInsets.all(10.0),
                              decoration: BoxDecoration(
                                color: Color(0xffDFDFDF),
                                shape: BoxShape.circle,
                              ),
                              child: Center(
                                child: Icon(
                                  Icons.arrow_back_ios_outlined,
                                  size: 20.0,
                                  color: Colors.black,
                                ),
                              ),
                            ),
                          ),
                        ),
                        title: Text(
                          S.of(context).cards,
                          style: AppStyle.textStyle().copyWith(
                              color: Colors.black,
                              fontWeight: FontWeight.w600,
                              fontSize: 21.0),
                        ),
                      ),
                      body: BlocListener(
                        bloc: CardsPage.cardBloc,
                        listener: (context, state) {
                          if (state is GetCardsSuccessState) {
                            CardsPage.cards.clear();
                            print('-----SUCCESS-----');
                            if (mounted)
                              setState(() {
                                CardsPage.cards = state.response.results ?? [];
                              });
                            try {
                              CardsPage.loading.value = false;
                            } catch (e) {}
                          }
                          if (state is DeleteCardSuccessState) {
                            CardsPage.loading.value = false;
                            CardsPage.cardBloc.add(GetCardsEvent());
                          }
                        },
                        child: BlocBuilder(
                          bloc: CardsPage.cardBloc,
                          builder: (context, state) {
                            if (state is CardLoadingError) {
                              return Center(
                                child: SizedBox(),
                              );
                            }
                            return (CardsPage.cards.length == 0 &&
                                    state is GetCardsSuccessState)
                                ? AddNewPage(
                                    text: "${S.of(context).no_cards}",
                                    subText:
                                        "${S.of(context).no_card_description}",
                                    btnText: "${S.of(context).add_card}",
                                    onTap: () async {
                                      Navigator.push(
                                        context,
                                        CupertinoPageRoute(
                                          builder: (context) => AddCardPage(),
                                        ),
                                      );
                                    },
                                  )
                                : RefreshIndicator(
                                    color: Colors.black,
                                    onRefresh: () async {
                                      CardsPage.loading = ValueNotifier(true);
                                      setState(() {});
                                      CardsPage.cardBloc.add(GetCardsEvent());
                                    },
                                    child: Center(
                                      child: Container(
                                        height: 87.0.h,
                                        child: SingleChildScrollView(
                                          physics:
                                              AlwaysScrollableScrollPhysics(),
                                          child: Column(
                                            children: List.generate(
                                              CardsPage.cards.length + 1,
                                              (index) {
                                                if (CardsPage.cards.length ==
                                                    index) {
                                                  return SizedBox(
                                                      height: 180.0);
                                                }
                                                // if (CardsPage.cards[index]
                                                //     .isVerified) {
                                                return Padding(
                                                  padding: const EdgeInsets
                                                          .symmetric(
                                                      vertical: 10.0,
                                                      horizontal: 10.0),
                                                  child: CardItem(
                                                    card:
                                                        CardsPage.cards[index],
                                                    gradientId: index % 8,
                                                  ),
                                                );
                                                // } else {
                                                //   // CardsPage
                                                //   //     .cardBloc.repository
                                                //   //     .deleteCard(CardsPage
                                                //   //         .cards[index].id);
                                                //   return SizedBox();
                                                // }
                                              },
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                  );
                          },
                        ),
                      ),
                    ),
                  ),
                )
              : NoConnectionScreen(
                  onTap: () {
                    Navigator.pushReplacement(
                        context, FadeRoute(page: CardsPage()));
                  },
                );
        });
  }
}
