import 'dart:convert';
import 'dart:io';
import 'package:app_hit_a_wod/src/blocs/box_calendar_page.bloc.dart';
import 'package:app_hit_a_wod/src/blocs/user_edit_form.bloc.dart';
import 'package:app_hit_a_wod/src/models/bi_training_session.model.dart';
import 'package:app_hit_a_wod/src/models/training_room.model.dart';
import 'package:app_hit_a_wod/src/models/training_workout.model.dart';
import 'package:app_hit_a_wod/src/models/user.model.dart';
import 'package:app_hit_a_wod/src/providers/auth.provider.dart';
import 'package:app_hit_a_wod/src/providers/user-subscriptions.provider.dart';
import 'package:app_hit_a_wod/src/styles.dart';
import 'package:app_hit_a_wod/src/utils/custom_training_session_action_button.dart/training_session_action_button.dart';
import 'package:app_hit_a_wod/src/utils/fontello/my_flutter_app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';


class TrainingSessionDetailPage extends StatefulWidget {
  @override
  _TrainingSessionDetailPageState createState() => _TrainingSessionDetailPageState();
}

class _TrainingSessionDetailPageState extends State<TrainingSessionDetailPage> {
  bool updated = false;
  BITrainingSession newts = null;
  Widget build(BuildContext context) {
    final double formWidth = 80;
    final auth = Provider.of<AuthProvider>(context);
    Map<String,dynamic> arguments = ModalRoute.of(context).settings.arguments;
    BITrainingSession ts;
    ts = arguments['trainingSession'];
    final UserSubscriptionsProvider us_provider = Provider.of<UserSubscriptionsProvider>(context);
    final BoxCalendarPageBloc bloc = BoxCalendarPageBloc(
      context: context, 
      box_id: us_provider.currentActiveSubscription.box.id, 
      day: arguments['day']
    );

    return neuScaffoldDetail(
      context: context,
      title: Text("Sesión de entrenamiento #${ts.id}", style: Theme.of(context).textTheme.subhead.copyWith(fontWeight: FontWeight.w500, fontSize: 18)),
      action: FlatButton(
        child: shaderContainer(Image.asset('assets/icon/logo.png', height: 35, width: 35,),'in'),
        onPressed: () {
          Navigator.of(context).popUntil(ModalRoute.withName('home'));
        }
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.symmetric(horizontal: 20),
        child: Container(
          width: double.infinity,
          child: Column(
            children: <Widget>[
              neuContainer(
                Column(
                  children: <Widget>[
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        neuChip(
                          Text('${ts.training_type.name}',style: Theme.of(context).textTheme.display2,),
                          colors: colors_list[colors_type[ts.training_type.slug]]
                        ),
                        Expanded(
                          child: Container(
                            height: 35.0,
                            alignment: Alignment.centerRight,
                            child: Column(
                              children: <Widget>[
                                Container(
                                  padding: EdgeInsets.only(),
                                  height: 15.0,
                                  alignment: Alignment.centerRight,
                                  child: Text('${DateFormat('dd').format(ts.date_start)} de ${DateFormat('MMMM').format(ts.date_start)} del ${DateFormat('yyyy').format(ts.date_start)}', style: Theme.of(context).textTheme.subtitle),
                                ),
                                SizedBox(height: 5.0),
                                Container(
                                  height: 15.0,
                                  alignment: Alignment.centerRight,
                                  child: Text('${DateFormat('kk:mm').format(ts.date_start.toLocal())} - ${DateFormat('kk:mm').format(ts.date_end.toLocal())}', style: Theme.of(context).textTheme.subtitle.copyWith(fontWeight: FontWeight.w400))
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                    _getPreliminarInfo(context,ts),
                    getMiniWorkout(context,ts.training_workout),
                    getAssists(context,ts.users,auth),
                    Container(
                      margin: EdgeInsets.only(top: 20.0),
                      alignment: Alignment.centerRight,
                      width: double.infinity,
                      child: neuTrainingSessionActionButton(
                        ts: newts!=null ? newts : ts,
                        onClicked: (newTs){
                          setState(() {
                            this.updated = true;
                            ts = newTs;
                            this.newts = newTs;
                            bloc.refreshTrainingSessions(us_provider.currentActiveSubscription.box.id, arguments['day']);
                          });
                        },
                        user: auth.currentUser,
                      )
                    )
                  ],
                ),
                margin: EdgeInsets.only(top: 20),
              )
            ],
          )
        )
      )
    );
  }

  getAssists(BuildContext context, List<User> users, AuthProvider auth) {
    return (users.length>0) ? neuContainer(
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text('Atletas apuntados', style: Theme.of(context).textTheme.subtitle,),
          SizedBox(height: 20.0,),
          Wrap(
            spacing: 5.0,
            runSpacing: 10.0,
            children: new List.generate(users.length, (i) => neuProfilePhoto(context,users[i],user_id: auth.currentUser.id)),
          )
        ],
      ),
      margin: EdgeInsets.only(top: 20),
      width: double.infinity
    ) : SizedBox();
  }

  _getPreliminarInfo(BuildContext context, BITrainingSession ts) {
    return neuContainer(
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          _getSala(context,ts),
          SizedBox(height: 10.0,),
          _getCoach(context,ts.coach),
        ],
      ),
      margin: EdgeInsets.symmetric(vertical: 20.0),
      width: double.infinity
    );
  }

  _getSala(BuildContext context, BITrainingSession ts) {
    return Wrap(
      spacing: 10.0,
      runSpacing: 10.0,
      children: <Widget>[
        neuChip(
          Text('Sala ${ts.training_room.name}',style: Theme.of(context).textTheme.display2)
        ),
        neuChip(
          Wrap(
            alignment: WrapAlignment.center,
            children: <Widget>[
              Icon(Icons.people, color: Colors.white, size: 16.0,),
              Container(
                height: 14.0,
                width: 25.0,
                alignment: Alignment.centerRight,
                child: Text('${ts.capacity!=null ? ts.capacity : '∞'}', style: Theme.of(context).textTheme.display2,textAlign: TextAlign.center,),
              )
            ],
          ),
          colors: secondaryShadow
        )
      ],
    );
  }

  _getCoach(BuildContext context,User coach) {
    return (coach!=null) ?
      Container(
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            neuProfilePhoto(context,coach,sizeInside: 60, sizeOutside: 70, margin: EdgeInsets.only( right: 20.0)),
            SizedBox(height: 5.0,),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text('Coach', style: Theme.of(context).textTheme.subtitle),
                SizedBox(height: 5.0,),
                Container(
                  width: 130,
                  child: Text('${coach.name + ' ' + coach.surnames}', style: Theme.of(context).textTheme.body1, overflow: TextOverflow.clip,),
                )
                
              ],
            )
          ],
        ),
      )
    :
      SizedBox(height: 0.0,width: 0.0,);
  }
}