import 'dart:collection';

import 'package:aitrainer_app/bloc/customer_change/customer_change_bloc.dart';
import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/model/sport.dart';
import 'package:aitrainer_app/util/app_localization.dart';
import 'package:aitrainer_app/repository/customer_repository.dart';
import 'package:aitrainer_app/model/fitness_state.dart';
import 'package:aitrainer_app/util/trans.dart';
import 'package:aitrainer_app/widgets/app_bar_min.dart';
import 'package:aitrainer_app/widgets/app_bar_progress.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:google_fonts/google_fonts.dart';

import '../bloc/customer_change/customer_change_bloc.dart';
import '../library/dropdown_search/dropdown_search.dart';

// ignore: must_be_immutable
class CustomerFitnessPage extends StatefulWidget {
  late _CustomerFitnessPageState _state;

  _CustomerFitnessPageState createState() {
    _state = _CustomerFitnessPageState();
    return _state;
  }
}

class _CustomerFitnessPageState extends State<CustomerFitnessPage> with Trans {
  String? selected;
  bool fulldata = false;

  @override
  Widget build(BuildContext context) {
    setContext(context);
    final double cWidth = MediaQuery.of(context).size.width * 0.75;
    CustomerRepository customerRepository;
    dynamic args = ModalRoute.of(context)!.settings.arguments;
    if (args is HashMap && args['personal_data'] != null) {
      fulldata = args['personal_data'];
      customerRepository = args['bloc'];
    } else {
      customerRepository = ModalRoute.of(context)!.settings.arguments as CustomerRepository;
    }

    PreferredSizeWidget _bar = AppBarMin(
      back: true,
    );
    if (!fulldata) {
      _bar = AppBarProgress(max: 50, min: 26);
    }
    return Scaffold(
        appBar: _bar,
        body: BlocProvider(
            create: (context) => CustomerChangeBloc(customerRepository: customerRepository),
            child: Builder(builder: (context) {
              // ignore: close_sinks
              CustomerChangeBloc changeBloc = BlocProvider.of<CustomerChangeBloc>(context);
              selected = changeBloc.selectedFitnessItem;
              if (selected == null) {
                selected = FitnessState.beginner;
              }
              return SingleChildScrollView(
                scrollDirection: Axis.vertical,
                child: Container(
                  padding: EdgeInsets.only(bottom: 200),
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('asset/image/WT_light_background.jpg'),
                      fit: BoxFit.cover,
                      alignment: Alignment.center,
                    ),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Divider(),
                      Wrap(
                          //runAlignment: WrapAlignment.center,
                          alignment: WrapAlignment.center,
                          children: [
                            Text(
                              t("Your Fitness State"),
                              textAlign: TextAlign.center,
                              style: GoogleFonts.archivoBlack(
                                color: Colors.orange,
                                fontSize: 30,
                                fontWeight: FontWeight.w900,
                              ),
                            )
                          ]),
                      Divider(),
                      TextButton(
                          style: TextButton.styleFrom(
                            padding: EdgeInsets.all(10.0),
                            shape: getShape(changeBloc, FitnessState.beginner),
                          ),
                          child: Container(
                              width: cWidth,
                              child: Column(
                                children: [
                                  Text(t("Beginner"),
                                      textWidthBasis: TextWidthBasis.longestLine,
                                      style: TextStyle(color: Colors.blue, fontSize: 32, fontFamily: 'Arial', fontWeight: FontWeight.w900)),
                                  Text(
                                    t("I am beginner"),
                                    style: TextStyle(color: Colors.black, fontSize: 20, fontFamily: 'Arial', fontWeight: FontWeight.w100),
                                  ),
                                ],
                              )),
                          onPressed: () => {
                                setState(() {
                                  selected = FitnessState.beginner;
                                  changeBloc.add(CustomerFitnessChange(fitness: selected!));
                                }),
                              }),
                      Divider(),
                      TextButton(
                          style: TextButton.styleFrom(
                            padding: EdgeInsets.all(10.0),
                            shape: getShape(changeBloc, FitnessState.intermediate),
                          ),
                          child: Container(
                            width: cWidth,
                            child: Column(
                              children: [
                                InkWell(
                                  child: Text(
                                    t("Intermediate"),
                                    style: TextStyle(color: Colors.blue, fontSize: 32, fontFamily: 'Arial', fontWeight: FontWeight.w900),
                                  ),
                                  highlightColor: Colors.white,
                                ),
                                InkWell(
                                  child: Text(
                                    t("I am intermediate"),
                                    style: TextStyle(color: Colors.black, fontSize: 20, fontFamily: 'Arial', fontWeight: FontWeight.w100),
                                  ),
                                  highlightColor: Colors.white,
                                ),
                              ],
                            ),
                          ),
                          onPressed: () => {
                                setState(() {
                                  selected = FitnessState.intermediate;
                                  changeBloc.add(CustomerFitnessChange(fitness: selected!));
                                  print(selected);
                                }),
                              }),
                      Divider(),
                      TextButton(
                          style: TextButton.styleFrom(
                            padding: EdgeInsets.all(10.0),
                            shape: getShape(changeBloc, FitnessState.advanced),
                          ),
                          child: Container(
                            width: cWidth,
                            child: Column(
                              children: [
                                InkWell(
                                  child: Text(
                                    t("Advanced"),
                                    style: TextStyle(color: Colors.blue, fontSize: 32, fontFamily: 'Arial', fontWeight: FontWeight.w900),
                                  ),
                                  highlightColor: Colors.white,
                                ),
                                InkWell(
                                  child: Text(
                                    t("I am advanced"),
                                    style: TextStyle(color: Colors.black, fontSize: 20, fontFamily: 'Arial', fontWeight: FontWeight.w100),
                                  ),
                                  highlightColor: Colors.white,
                                ),
                              ],
                            ),
                          ),
                          onPressed: () => {
                                setState(() {
                                  selected = FitnessState.advanced;
                                  changeBloc.add(CustomerFitnessChange(fitness: selected!));
                                  print(selected);
                                }),
                              }),
                      Divider(),
                      TextButton(
                          style: TextButton.styleFrom(
                            padding: EdgeInsets.all(10.0),
                            shape: getShape(changeBloc, FitnessState.professional),
                          ),
                          child: Container(
                            width: cWidth,
                            child: Column(
                              children: [
                                InkWell(
                                  child: Text(
                                    AppLocalizations.of(context)!.translate("Professional"),
                                    style: TextStyle(color: Colors.blue, fontSize: 32, fontFamily: 'Arial', fontWeight: FontWeight.w900),
                                  ),
                                  highlightColor: Colors.white,
                                ),
                                InkWell(
                                  child: Text(
                                    AppLocalizations.of(context)!.translate("I am professional"),
                                    style: TextStyle(color: Colors.black, fontSize: 20, fontFamily: 'Arial', fontWeight: FontWeight.w100),
                                  ),
                                  highlightColor: Colors.white,
                                ),
                              ],
                            ),
                          ),
                          onPressed: () => {
                                setState(() {
                                  selected = FitnessState.professional;
                                  changeBloc.add(CustomerFitnessChange(fitness: selected!));
                                  print(selected);
                                }),
                              }),
                      Divider(),
                      Text(
                        t("Your Primary Sport") + ":",
                        textAlign: TextAlign.center,
                        style: GoogleFonts.archivoBlack(
                          color: Colors.orange,
                          fontSize: 20,
                        ),
                      ),
                      getSport(changeBloc),
                      Divider(),
                      ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          onPrimary: Colors.white,
                          primary: Colors.orange,
                        ),
                        child: Text(fulldata ? t("Save") : t("Next")),
                        onPressed: () => {
                          changeBloc.add(CustomerSave()),
                          Navigator.of(context).pop(),
                          if (!fulldata) {Navigator.of(context).pushNamed("customerBodyTypePage", arguments: customerRepository)}
                        },
                      )
                    ],
                  ),
                ),
              );
            })));
  }

  dynamic getShape(CustomerChangeBloc changeBloc, String fitnessLevel) {
    String? selected = changeBloc.selectedFitnessItem;
    dynamic returnCode = (selected == fitnessLevel)
        ? RoundedRectangleBorder(
            side: BorderSide(width: 4, color: Colors.orange),
          )
        : RoundedRectangleBorder(
            side: BorderSide(width: 1, color: Colors.blue),
          );
    //return
    return returnCode;
  }

  Widget getSport(CustomerChangeBloc bloc) {
    Sport? selected = bloc.selectedSport;
    return Container(
        padding: EdgeInsets.only(left: 65, right: 65),
        child: DropdownSearch<Sport>(
          dropdownSearchDecoration: InputDecoration(
            contentPadding: EdgeInsets.only(left: 15, top: 5, bottom: 5),
            labelText: t("Sport"),
            labelStyle: GoogleFonts.inter(fontSize: 16, color: Colors.indigo),
            //fillColor: Colors.black38,
            filled: false,
            border: OutlineInputBorder(
              gapPadding: 2.0,
              borderRadius: BorderRadius.circular(12.0),
              borderSide: BorderSide(color: Colors.blue, width: 0.4),
            ),
          ),
          mode: Mode.MENU,
          compareFn: (Sport? i, Sport? s) {
            if (i == null || s == null) {
              return false;
            } else {
              return i.sportId == s.sportId;
            }
          },
          showSelectedItem: true,
          selectedItem: selected,
          itemAsString: (data) => t(data.sportNameTranslation),
          onChanged: (data) {
            bloc.add(CustomerSportChange(sport: data));
          },
          dropdownBuilder: _customDropDownItem,
          popupItemBuilder: _customMenuBuilder,
          popupBarrierColor: Colors.white10,
          //popupBackgroundColor: Colors.yellow,
          items: Cache().getSports(),
          dropDownButton: Icon(
            Icons.arrow_drop_down,
            color: Colors.indigo,
          ),
        ));
    //items: FitnessItem().toList()));
  }

  Widget _customMenuBuilder(BuildContext context, Sport sport, bool isSelected) {
    return Container(
      decoration: !isSelected
          ? BoxDecoration(color: Colors.grey[300])
          : BoxDecoration(
              border: Border.all(color: Colors.blue),
              borderRadius: BorderRadius.circular(12),
              color: Colors.grey[100],
            ),
      child: ListTile(
        selected: isSelected,
        title: Text(
          t(sport.sportNameTranslation),
          style: GoogleFonts.archivoBlack(fontSize: 20, color: Colors.blue[600]),
        ),
        subtitle: Text(
          t(sport.name),
          style: GoogleFonts.inter(fontSize: 12, color: Colors.blue[600]),
        ),
      ),
    );
  }

  Widget _customDropDownItem(BuildContext context, Sport? item, String itemDesignation) {
    return Container(
      child: (item == null)
          ? ListTile(
              contentPadding: EdgeInsets.all(0),
              title: Text(
                t("No item selected"),
                style: GoogleFonts.inter(fontSize: 14, color: Colors.blue[600]),
              ),
            )
          : ListTile(
              contentPadding: EdgeInsets.all(0),
              title: Text(
                t(item.sportNameTranslation),
                style: GoogleFonts.archivoBlack(fontSize: 20, color: Colors.blue[600]),
              ),
              subtitle: Text(
                t(item.name),
                style: GoogleFonts.inter(fontSize: 12, color: Colors.blue[600]),
              ),
            ),
    );
  }
}
