import 'dart:async';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';
import 'package:mohem_flutter_app/classes/colors.dart';
import 'package:mohem_flutter_app/classes/decorations_helper.dart';
import 'package:mohem_flutter_app/classes/lottie_consts.dart';
import 'package:mohem_flutter_app/extensions/int_extensions.dart';
import 'package:mohem_flutter_app/extensions/string_extensions.dart';
import 'package:mohem_flutter_app/extensions/widget_extensions.dart';
import 'package:mohem_flutter_app/generated/locale_keys.g.dart';
import 'package:mohem_flutter_app/ui/marathon/marathon_provider.dart';
import 'package:mohem_flutter_app/ui/marathon/widgets/custom_status_widget.dart';
import 'package:mohem_flutter_app/ui/marathon/widgets/question_card.dart';
import 'package:mohem_flutter_app/ui/marathon/widgets/question_card_builder.dart';
import 'package:mohem_flutter_app/widgets/app_bar_widget.dart';
import 'package:provider/provider.dart';

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

  @override
  Widget build(BuildContext context) {
    MarathonProvider provider = context.watch<MarathonProvider>();
    return WillPopScope(
      child: Scaffold(
        appBar: AppBarWidget(context, title: LocaleKeys.brainMarathon.tr()),
        body: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              20.height,
              MarathonProgressContainer(provider: provider).paddingOnly(left: 21, right: 21),
              QuestionCardBuilder(
                onQuestion: (BuildContext context) => QuestionCard(provider: provider),
                onCompleted: (BuildContext context) => CustomStatusWidget(
                  asset: Lottie.asset(MyLottieConsts.allQuestions, height: 200),
                  title: LocaleKeys.congrats.tr().toText22(color: MyColors.greenColor),
                  subTitle: LocaleKeys.allQuestionsCorrect.toText18(color: MyColors.darkTextColor),
                ),
                onCorrectAnswer: (BuildContext context) => CustomStatusWidget(
                  asset: Lottie.asset(MyLottieConsts.allQuestions, height: 200),
                  title: LocaleKeys.congrats.tr().toText22(color: MyColors.greenColor),
                  subTitle: LocaleKeys.yourAnswerCorrect.toText18(color: MyColors.darkTextColor),
                ),
                onWinner: (BuildContext context) => QuestionCard(provider: provider),
                onWrongAnswer: (BuildContext context) => CustomStatusWidget(
                  asset: Image.asset(MyLottieConsts.wrongAnswerGif, height: 200),
                  title: const Text(""),
                  subTitle: LocaleKeys.wrongAnswer.tr().toText18(color: MyColors.darkTextColor),
                ),
                onSkippedAnswer: (BuildContext context) => CustomStatusWidget(
                  asset: Image.asset(MyLottieConsts.wrongAnswerGif, height: 200),
                  title: const Text(""),
                  subTitle: LocaleKeys.youMissedTheQuestion.tr().toText18(color: MyColors.darkTextColor),
                ),
                questionCardStatus: provider.questionCardStatus,
                onFindingWinner: (BuildContext context) => CustomStatusWidget(
                  asset: Lottie.asset(MyLottieConsts.winnerLottie, height: 168),
                  title: LocaleKeys.fingersCrossed.tr().toText22(color: MyColors.greenColor),
                  subTitle: LocaleKeys.winnerSelectedRandomly.tr().toText18(color: MyColors.darkTextColor),
                ),
              ).paddingOnly(top: 12, left: 21, right: 21),
            ],
          ),
        ),
      ),
      onWillPop: () {
        provider.resetValues();
        return Future<bool>.value(true);
      },
    );
  }
}

class MarathonProgressContainer extends StatefulWidget {
  final MarathonProvider provider;

  const MarathonProgressContainer({Key? key, required this.provider}) : super(key: key);

  @override
  State<MarathonProgressContainer> createState() => _MarathonProgressContainerState();
}

class _MarathonProgressContainerState extends State<MarathonProgressContainer> {
  @override
  void initState() {
    scheduleMicrotask(() {
      widget.provider.startTimer(context);
    });
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      decoration: MyDecorations.shadowDecoration,
      padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 13),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Container(
                decoration: BoxDecoration(color: MyColors.greenColor, borderRadius: BorderRadius.circular(5)),
                padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 8),
                child: "${widget.provider.currentQuestionNumber.toString()} / ${widget.provider.marathonDetailModel.totalQuestions.toString()}  ${LocaleKeys.question.tr()}"
                    .toText12(color: MyColors.white),
              ),
              "${widget.provider.totalMarathoners} ${LocaleKeys.marathoners.tr()}".toText14(),
              "00:${widget.provider.currentQuestionTime < 10 ? "0${widget.provider.currentQuestionTime}" : widget.provider.currentQuestionTime}"
                  .toText18(color: widget.provider.currentQuestionTime < 5 ? MyColors.redColor : MyColors.black),
            ],
          ),
          12.height,
          stepper(widget.provider.currentQuestionNumber),
          8.height,
          Row(
            children: <Widget>[
              "${((widget.provider.currentQuestionNumber / widget.provider.marathonDetailModel.totalQuestions!) * 100).toInt()}% ${LocaleKeys.completed.tr()}".toText14(),
            ],
          ),
        ],
      ),
    );
  }

  Widget stepper(int value) {
    return SizedBox(
      width: double.infinity,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          for (int i = 0; i < 10; i++)
            if (value <= i) roundContainer(MyColors.lightGreyDeColor, i != 0) else roundContainer(MyColors.greenColor, i != 0)
        ],
      ),
    );
  }

  Widget roundContainer(Color color, bool isNeedLeftBorder) {
    if (isNeedLeftBorder) {
      return Row(
        children: [
          Divider(thickness: 6, color: color).expanded,
          Container(
            width: 10,
            height: 10,
            decoration: BoxDecoration(shape: BoxShape.circle, color: color),
          ),
        ],
      ).expanded;
    }

    return Container(
      width: 10,
      height: 10,
      decoration: BoxDecoration(shape: BoxShape.circle, color: color),
    );
  }
}

//                InkWell(
//                   onTap: () {
//                     Navigator.pushReplacementNamed(
//                       context,
//                       AppRoutes.marathonWinnerSelection,
//                     );
//                   },
//                   child: CustomStatusWidget(
//                     asset: Lottie.asset(
//                       MyLottieConsts.allQuestions,
//                       height: 200,
//                     ),
//                     title: Text(
//                       LocaleKeys.congrats.tr(),
//                       style: const TextStyle(
//                         height: 23 / 24,
//                         color: MyColors.greenColor,
//                         fontSize: 27,
//                         letterSpacing: -1,
//                         fontWeight: FontWeight.w600,
//                       ),
//                     ),
//                     subTitle: Text(
//                       LocaleKeys.allQuestionsCorrect.tr(),
//                       textAlign: TextAlign.center,
//                       style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: MyColors.darkTextColor, letterSpacing: -1.08),
//                     ),
//                   ).paddingOnly(top: 12, left: 21, right: 21),
//                 )
