import 'dart:async';

import 'package:aitrainer_app/bloc/menu/menu_bloc.dart';
import 'package:aitrainer_app/bloc/timer/timer_bloc.dart';
import 'package:aitrainer_app/util/app_localization.dart';
import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/repository/exercise_repository.dart';
import 'package:aitrainer_app/util/common.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:percent_indicator/linear_percent_indicator.dart';
import 'package:rainbow_color/rainbow_color.dart';

import 'dialog_html.dart';

class AppBarNav extends StatefulWidget implements PreferredSizeWidget {
  final MenuBloc? menuBloc;
  final bool? isMenu;
  final int? depth;
  final VoidCallback? onTap;
  AppBarNav({this.menuBloc, this.isMenu, this.depth, this.onTap});

  @override
  _AppBarNav createState() => _AppBarNav();

  @override
  Size get preferredSize => const Size.fromHeight(50);
}

class _AppBarNav extends State<AppBarNav> with SingleTickerProviderStateMixin, Common {
  late Animation<Color> colorAnim;
  late AnimationController colorController;
  late MenuBloc menuBloc;

  @override
  void initState() {
    colorController = AnimationController(duration: Duration(seconds: 4), vsync: this);

    colorAnim = RainbowColorTween([
      Colors.white70,
      Colors.blueGrey,
      Colors.blueAccent,
      Colors.lightBlue,
      Colors.lightBlueAccent,
      Colors.yellowAccent,
      Colors.orange,
      Colors.orangeAccent,
      Colors.yellowAccent,
      Color(0xffcce6ff)
    ]).animate(colorController)
      ..addListener(() {
        setState(() {});
      })
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          Timer(Duration(seconds: 10), () {
            if (mounted) {
              colorController.forward();
            }
          });
        } else if (status == AnimationStatus.dismissed) {
          colorController.forward();
        }
      });
    colorController.forward();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    menuBloc = BlocProvider.of<MenuBloc>(context);
    // ignore: close_sinks
    final TimerBloc timerBloc = BlocProvider.of<TimerBloc>(context);

    return AppBar(
        backgroundColor: Colors.black,
        title: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            getAnimatedWidget(),
            Stack(
              children: [
                Image.asset(
                  'asset/image/WT_long_logo.png',
                  height: 45.0,
                ),
                getTestServer(),
              ],
            ),
          ],
        ),
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () {
            timerBloc.add(TimerEnd(duration: 0));
            print("tapping ${widget.onTap}");
            if (widget.onTap != null) {
              print("tap");
              widget.onTap!();
            }
            if (widget.isMenu != null) {
              if (menuBloc.workoutItem != null) {
                menuBloc.add(MenuTreeUp(parent: menuBloc.workoutItem!.parent));
              }
            } else if (widget.depth != null) {
              if (widget.depth == 0) {
                Navigator.of(context).popAndPushNamed('home');
              } else {
                Navigator.of(context).pop();
              }
            }
          },
        ));
  }

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

  Widget getTestServer() {
    if (Cache().liveServer) {
      return Container();
    } else {
      return Text("TEST",
          style: GoogleFonts.archivoBlack(
            color: Colors.red,
            fontWeight: FontWeight.bold,
            shadows: <Shadow>[
              Shadow(
                offset: Offset(5.0, 5.0),
                blurRadius: 12.0,
                color: Colors.black54,
              ),
              Shadow(
                offset: Offset(-3.0, 3.0),
                blurRadius: 12.0,
                color: Colors.black54,
              ),
            ],
          ));
    }
  }

  Widget getAnimatedWidget() {
    double cWidth = mediaSizeWidth(context);
    double percent = Cache().getPercentExercises();
    if (percent == -1 || percent.isNaN) {
      menuBloc.menuTreeRepository.createTree();
      ExerciseRepository exerciseRepository = ExerciseRepository();
      exerciseRepository.getBaseExerciseFinishedPercent();
      percent = Cache().getPercentExercises();
      if (percent == -1) {
        percent = 0;
      }
    }
    if (percent.isNaN) {
      percent = 0;
    }
    int sizeExerciseList = Cache().getExercises() == null ? 0 : Cache().getExercises()!.length;
    if (sizeExerciseList == 0) {
      String text = Cache().userLoggedIn == null
          ? AppLocalizations.of(context)!.translate("Please log in")
          : AppLocalizations.of(context)!.translate("Make your first test");
      double fontSize = text.length > 24 ? 13 : 16;
      return Stack(alignment: Alignment.topLeft, children: [
        GestureDetector(
            onTap: () => progressExplanation(),
            child: Text(
              text,
              style: TextStyle(fontSize: fontSize, color: colorAnim.value, shadows: [Shadow(color: Colors.purple, blurRadius: 15)]),
            )),
      ]);
    } else {
      return Stack(
        alignment: Alignment.topLeft,
        children: [
          GestureDetector(
            onTap: () => progressExplanation(),
            child: LinearPercentIndicator(
              width: cWidth / 4,
              lineHeight: 14.0,
              percent: percent,
              center: Text(
                (percent * 100).toStringAsFixed(0) + "% " + AppLocalizations.of(context)!.translate("finished"),
                style: new TextStyle(fontSize: 10.0),
              ),
              trailing: Icon(
                percent > 0.6 ? Icons.mood : Icons.mood_bad,
                color: colorAnim.value,
              ),
              linearStrokeCap: LinearStrokeCap.roundAll,
              backgroundColor: colorAnim.value,
              progressColor: Color(0xff73e600),
              animation: true,
            ),
          )
        ],
      );
    }
  }

  void progressExplanation() {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return DialogHTML(
            title: AppLocalizations.of(context)!.translate("Progressindicator for the tests"),
            htmlData: AppLocalizations.of(context)!.translate("Progressindicator_desc"),
          );
        });
  }
}