import 'dart:collection';

import 'package:aitrainer_app/bloc/development_sizes/development_sizes_bloc.dart';
import 'package:aitrainer_app/library/custom_icon_icons.dart';
import 'package:aitrainer_app/model/property.dart';
import 'package:aitrainer_app/repository/customer_repository.dart';
import 'package:aitrainer_app/util/trans.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';
import '../widgets/app_bar.dart';

class SizesDevelopmentPage extends StatefulWidget {
  const SizesDevelopmentPage();

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

class _SizeState extends State<SizesDevelopmentPage> with Trans {
  @override
  Widget build(BuildContext context) {
    setContext(context);
    return BlocProvider(
      create: (context) => DevelopmentSizesBloc(customerRepository: CustomerRepository())..add(DevelopmentSizesLoad()),
      child: BlocConsumer<DevelopmentSizesBloc, DevelopmentSizesState>(listener: (context, state) {
        if (state is DevelopmentSizesError) {
          ScaffoldMessenger.of(context)
              .showSnackBar((SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white)))));
        }
      }, builder: (context, state) {
        final bloc = BlocProvider.of<DevelopmentSizesBloc>(context);
        return ModalProgressHUD(
          child: getForm(bloc),
          inAsyncCall: state is DevelopmentSizesLoad,
          opacity: 0.5,
          color: Colors.black54,
          progressIndicator: CircularProgressIndicator(),
        );
      }),
    );
  }

  Widget getForm(DevelopmentSizesBloc bloc) {
    return Scaffold(
        resizeToAvoidBottomInset: true,
        appBar: AppBarNav(depth: 1),
        body: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('asset/image/WT_black_background.jpg'),
              fit: BoxFit.fill,
              alignment: Alignment.center,
            ),
          ),
          child: SafeArea(
              child: Container(
                  padding: EdgeInsets.only(top: 10),
                  child: SingleChildScrollView(
                      child: Column(crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [
                    getHeader(bloc),
                    Stack(
                      alignment: Alignment.center,
                      children: getSizeFigure(bloc),
                    )
                  ])))),
        ));
  }

  List<Widget> getSizeFigure(DevelopmentSizesBloc bloc) {
    double mediaWidth = MediaQuery.of(context).size.width * .8;
    double mediaHeight = MediaQuery.of(context).size.height * .8;

    bloc.customerRepository.setMediaDimensions(mediaWidth, mediaHeight);
    List<Widget> list = [];

    list.add(
      bloc.isMan
          ? Image.asset(
              "asset/image/man_sizes.png",
              height: mediaHeight,
              width: mediaWidth,
            )
          : Image.asset(
              "asset/image/woman_sizes.png",
              height: mediaHeight,
              width: mediaWidth,
            ),
    );
    list.add(Positioned(
      top: bloc.customerRepository.getWeightCoordinate(bloc.isMan, isTop: true)!.toDouble(),
      left: bloc.customerRepository.getWeightCoordinate(bloc.isMan, isTop: false, isLeft: true)!.toDouble() - 45,
      child: GestureDetector(
          child: Image.asset(
        "asset/image/merleg.png",
        height: 120,
        width: 120,
        color: Colors.blue,
      )),
    ));

    list.addAll(getSizeElements(bloc));

    return list;
  }

  List<Widget> getSizeElements(DevelopmentSizesBloc bloc) {
    List<Widget> list = [];

    bloc.customerRepository.manSizes.forEach((element) {
      list.add(
        Positioned(
            top: element.top!.toDouble(),
            left: element.left!.toDouble(),
            child: element.value != 0
                ? Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      color: bloc.isMan ? Colors.green[800] : Color(0xFFEA776C),
                      borderRadius: BorderRadius.all(
                        Radius.circular(40),
                      ),
                    ),
                    padding: EdgeInsets.only(left: 1, top: 1, right: 1, bottom: 1),
                    child: TextButton(
                      child: Text(
                        bloc.customerRepository.getCustomerProperty(element.propertyName)!.propertyValue.toStringAsFixed(0),
                        style: GoogleFonts.inter(color: Colors.white, fontSize: 12),
                      ),
                      onPressed: () => onPressed(element, bloc, element.propertyName),
                    ))
                : Container(
                    width: 23,
                    height: 23,
                    padding: EdgeInsets.zero,
                    decoration: BoxDecoration(
                      color: bloc.isMan ? Colors.white10 : Color(0xFFEA776C),
                      borderRadius: BorderRadius.all(
                        Radius.circular(23),
                      ),
                    ),
                    child: IconButton(
                      icon: Icon(CustomIcon.minus_circle, color: Colors.red),
                      padding: EdgeInsets.zero,
                      color: Colors.red[800],
                      splashColor: Colors.amber,
                      onPressed: () => onPressed(element, bloc, element.propertyName),
                    ))),
      );
    });

    return list;
  }

  void onPressed(Property element, DevelopmentSizesBloc bloc, String propertyName) {
    HashMap<String, dynamic> args = HashMap();
    args['customerRepository'] = bloc.customerRepository;
    args['property'] = element;
    args['title'] = t("Size development") + ": " + t(propertyName);
    Navigator.of(context).pushNamed('developmentDiagramPage', arguments: args);
  }

  Widget getHeader(DevelopmentSizesBloc bloc) {
    return Card(
        color: Colors.white60,
        child: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('asset/image/WT_plainblack_background.jpg'),
                fit: BoxFit.cover,
                alignment: Alignment.center,
              ),
            ),
            padding: EdgeInsets.only(left: 10, right: 5, top: 12, bottom: 8),
            child: Column(children: [
              Wrap(
                //mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Icon(
                    Icons.info,
                    color: Colors.orangeAccent,
                  ),
                  Text("  "),
                  Text(
                    t("Red icon means you have not saved this size."),
                    //overflow: TextOverflow.clip,
                    style: GoogleFonts.inter(
                      fontSize: 12,
                      color: Colors.white,
                    ),
                  ),
                ],
              ),
              Text(
                t("Tap on the green icon to see your development in a diagram"),
                //overflow: TextOverflow.clip,
                style: GoogleFonts.inter(
                  fontSize: 12,
                  color: Colors.white,
                ),
              ),
            ])));
  }
}
