import 'package:app_hit_a_wod/src/blocs/box_calendar_page.bloc.dart';
import 'package:app_hit_a_wod/src/models/subscription_selection.model.dart';
import 'package:app_hit_a_wod/src/models/bi_training_session.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/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:app_hit_a_wod/src/styles.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:rxdart/rxdart.dart';
import 'package:app_hit_a_wod/src/utils/custom_calendar/calendar_neu.dart';


class BoxCalendarPage extends StatefulWidget {
  const BoxCalendarPage({Key key}) : super(key: key);

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

class _BoxCalendarPageState extends State<BoxCalendarPage> {
  DateTime day = DateTime.now();

  @override
  Widget build(BuildContext context) {
    //inicialitzem data
    final AuthProvider auth = Provider.of<AuthProvider>(context);
    final UserSubscriptionsProvider us_provider = Provider.of<UserSubscriptionsProvider>(context);
    final _now = DateTime.now();
    List<BITrainingSession> trainingSession;
    final BoxCalendarPageBloc bloc = BoxCalendarPageBloc(
      context: context, 
      box_id: us_provider.currentActiveSubscription.box.id, 
      day: day
    );

    return RefreshIndicator(
      onRefresh: () async {
        List<Future> list = [];
        list.add(bloc.refreshTrainingSessions(us_provider.currentActiveSubscription.box.id, day));
        await Future.wait(list);
        return;
      },
      color: colors["primary"],
      displacement: 1,
      child: Stack(
        children: <Widget>[
          SingleChildScrollView(
            physics: AlwaysScrollableScrollPhysics(),
            padding: EdgeInsets.only(left: 20, right: 20, bottom: 20, top: 265),
            child: StreamBuilder(
              stream: CombineLatestStream.combine3(auth.userStream, us_provider.activeStream, bloc.trainingSessionStream, (user, ss, List<BITrainingSession> trainingSession) => {"user": user, "ss": ss, "trainingSession": trainingSession}),
              builder: (BuildContext context, AsyncSnapshot<dynamic> data) {
                if(data.connectionState == ConnectionState.active && data.hasData) {
                  final User user = data.data["user"];
                  final SubscriptionSelection ss = data.data["ss"];
                  trainingSession = data.data["trainingSession"];
                  if(trainingSession!=null && trainingSession.length>0){
                    final ts_cards = new List.generate(trainingSession.length, 
                                                        (i)=>_generateTrainingSessionCard(context,trainingSession[i],i,user, 
                                                              neuTrainingSessionActionButton(
                                                                ts: trainingSession[i],
                                                                onClicked: (newTs){
                                                                  if (this.mounted) {
                                                                    setState(() {
                                                                      trainingSession[i] = newTs;
                                                                    });
                                                                  }
                                                                },
                                                                user: user,
                                                              )
                                                        )
                    );

                    return Container(
                      width: double.infinity,
                      child: Wrap(
                        runSpacing: 20.0,
                        children: ts_cards
                      ),
                    );
                  } else if (trainingSession==null) {
                    return Container(
                      width: double.infinity,
                      child: Wrap(
                        runSpacing: 20.0,
                        children: <Widget>[
                        neuSkeletonCard(200, double.infinity),
                        neuSkeletonCard(200, double.infinity),
                        neuSkeletonCard(200, double.infinity)
                      ]
                      ),
                    );
                  } else {
                    return neuContainer(
                      Column(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
                        shaderContainer(Icon(MyFlutterApp.exhaust, size: 80,), 'letter', [colors["primary"], colors["secondary"]]),
                        SizedBox(height: 50),
                        Text("Vaya, no parece que haya ninguna sesión de entrenamiento planeado aún...", style: Theme.of(context).textTheme.body1)
                      ]),
                      width: double.infinity,
                      height: 250
                    );
                  }
                }
                else {
                  final size_circle = MediaQuery.of(context).size.width/3.7;
                  final size_button = MediaQuery.of(context).size.width/2.5;
                  return Container(
                    child: Column(
                      children: <Widget>[
                        neuSkeletonCard(150, double.infinity),
                        SizedBox(height: 20),
                        neuSkeletonCard(150, double.infinity),
                        SizedBox(height: 20),
                        neuSkeletonCard(150, double.infinity),
                        SizedBox(height: 20),
                        neuSkeletonCard(150, double.infinity),
                      ],
                    )
                  );
                }
              }
            ),
          ),
          SingleChildScrollView(
            physics: NeverScrollableScrollPhysics(),
            child: _calendar(us_provider.currentActiveSubscription.box.id,bloc),
          )
        ],
      ),
    );
  }

  Widget _generateTrainingSessionCard(BuildContext context, BITrainingSession ts, int index, User user, Widget button) {
    return neuContainer(
      InkWell(
        child: Wrap(
          runSpacing: 10.0,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                neuChip(
                  Text('${ts.training_type.name}',style: TextStyle(color: Colors.white),),
                  colors: colors_list[colors_type[ts.training_type.slug]]
                ),
                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)
                ),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Expanded(
                  child: Container(
                    width: MediaQuery.of(context).size.width * 0.5 - 40.0,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          child: Text('Sala principal', style: Theme.of(context).textTheme.subtitle),
                        ),
                        SizedBox(height: 5.0,),
                        Container(
                          child: Text('Capacidad: ${ts.capacity!=null ? ts.capacity : '∞'}', style: Theme.of(context).textTheme.body1),
                        )
                      ],
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    width: MediaQuery.of(context).size.width * 0.5 - 40.0,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          alignment: Alignment.centerRight,
                          width: double.infinity,
                          child: _getParticipants(context,ts.users,user)                  
                        ),
                      ],
                    ),
                  ),
                )
              ]
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: <Widget>[
                Expanded(
                  child: _getCoach(context,ts.coach),
                ),
                Expanded(
                  child: button
                )
              ],
            )
            
          ],
        ),
        onTap: () {
          Navigator.pushNamed(context, 'training-session-detail', arguments: {"trainingSession": ts, "day": day});
        },
      )
    );
  }

  _getCoach(BuildContext context,User coach) {
    return (coach!=null) ?
      Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text('Coach', style: Theme.of(context).textTheme.subtitle),
            SizedBox(height: 5.0,),
            Row(
              children: <Widget>[
                neuProfilePhoto(context,coach),
                SizedBox(width: 5.0,),
                Container(
                  width: MediaQuery.of(context).size.width * 0.5 - 110.0,
                  child: Text('${coach.name + ' ' + coach.surnames}', style: Theme.of(context).textTheme.body1, overflow: TextOverflow.fade,),
                )
              ],
            )
          ],
        ),
      )
    :
      SizedBox(height: 0.0,width: 0.0,);
  }

  _getParticipants(BuildContext context,List<User> users, User user) {
    final user_size = users.length>=3 ? 3 : users.length;
    users = _orderParticipants(users,user,user_size-1);
    return (users!= null && users.length>0) ? 
      Align(
        alignment: Alignment.centerRight,
        child: Container(          
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Stack(
                alignment: Alignment.centerRight,
                children: new List.generate(user_size, (i) => _getImageParticipant(context,users[i],i,user_size,user)),
              ),
              ( users.length!=user_size && users.length>0 ) ? Text(" + ${users.length - user_size}", style: Theme.of(context).textTheme.body1) : Text('')
            ],
          ),
        ),
      )
    :
      Text('0');
  }

  _orderParticipants(List<User> users, User currentUser, int user_pos) {
    var me = users.firstWhere((u) => u.id == currentUser.id, orElse: () => null);
    if(me!=null) {
      users.removeWhere((element) => element.id == currentUser.id);
      users.insert(user_pos, me);
    }
    return users;
  }

  _getImageParticipant(BuildContext context,User user, int index, int user_size, User currentUser) {
    return neuProfilePhoto(context,user,margin: EdgeInsets.only(right:(30.0*(user_size-(index+1)))),user_id: currentUser.id );
  }

  _calendar(int box_id, BoxCalendarPageBloc bloc) {
    return Stack(
      children: <Widget>[
        Container(
          height: 50,
          color: neuColor,
        ),
        Container(
          padding: EdgeInsets.all(20.0),
          decoration: BoxDecoration(),
          child: neuCalendar(
            isExpandable: true,
            showCalendarPickerIcon: false,
            showTodayAction: true,
            onDateSelected: (DateTime d) {
              bloc.refreshTrainingSessions(box_id, d);
              day = d;
            },
          ),
        ),
      ],
    );
  }
}