import 'package:app_hit_a_wod/src/models/subscription_selection.model.dart';
import 'package:app_hit_a_wod/src/models/user_subscription.model.dart';
import 'package:app_hit_a_wod/src/providers/api.provider.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:rxdart/subjects.dart';

import '../styles.dart';

class UserSubscriptionsProvider {

  static final _ACTIVE_SUBSCRIPTION_ID_KEY = "haw_active_subscription_id";

  //all subscriptions
  BehaviorSubject<List<SubscriptionSelection>> _subscriptionsSubject;
  Stream<List<SubscriptionSelection>> get stream => _subscriptionsSubject.asBroadcastStream();
  get currentSubscriptions => _subscriptionsSubject.value;

  //active subscription
  BehaviorSubject<SubscriptionSelection> _activeSubscriptionSubject;
  Stream<SubscriptionSelection> get activeStream => _activeSubscriptionSubject.asBroadcastStream();
  SubscriptionSelection get currentActiveSubscription => _activeSubscriptionSubject.value;

  FlutterSecureStorage _storage;

  //show subscriptions dialog observer
  BuildContext _context;

  //handle stripe provider
  ApiProvider _api;

  //constructor + singleton
  static UserSubscriptionsProvider _instancia;
  factory UserSubscriptionsProvider(BuildContext context, ApiProvider api) {
    if(_instancia==null) {
      _instancia = UserSubscriptionsProvider._internal(context, api);
    }
    return _instancia;
  }

  UserSubscriptionsProvider._internal(BuildContext this._context, ApiProvider this._api) {
    _subscriptionsSubject = new BehaviorSubject();
    _activeSubscriptionSubject = new BehaviorSubject();
    _storage = new FlutterSecureStorage();
  }

  setSubscriptions(List<SubscriptionSelection> uss) async {
    final String temp_sub_active_id = await _storage.read(key: _ACTIVE_SUBSCRIPTION_ID_KEY);
    final int user_subscription_active_id = temp_sub_active_id==null ? null : int.parse(temp_sub_active_id);
    int subscription_activated_index = -1;
    if(uss==null) uss = [];

    //nomes volem les de nivell box
    uss = uss.where((s) => s.level!="Company").toList();

    uss.asMap().forEach((i, ss) {
      if(user_subscription_active_id!=null && ss.us.id==user_subscription_active_id && subscription_activated_index==-1) {
        ss.active = true;
        subscription_activated_index = i;
      }
    });

    this._subscriptionsSubject.sink.add(uss);

    if(subscription_activated_index==-1) {
      await this.setActiveSubscription(0);
    }
    else await this.setActiveSubscription(subscription_activated_index);

  }

  removeSubscriptions() async {
    this._subscriptionsSubject.sink.add(null);
    await _storage.delete(key: _ACTIVE_SUBSCRIPTION_ID_KEY);
  }

  setActiveSubscription(int index) async {
    List<SubscriptionSelection> res = this.currentSubscriptions;
    res.forEach((s) {
      if(s.active) s.active = false;
    });

    if(index==null) {
      this._subscriptionsSubject.sink.add(null);
      this._activeSubscriptionSubject.sink.add(null);
      await _storage.delete(key: _ACTIVE_SUBSCRIPTION_ID_KEY);
    }
    else {

      if(res!=null && index>= res.length) throw Exception("Index is higher than subscriptions length");

      res[index].active = true;
      SubscriptionSelection active = res[index];

      await _storage.write(key: _ACTIVE_SUBSCRIPTION_ID_KEY, value: active.us.id.toString());
      this._subscriptionsSubject.sink.add(res);
      this._activeSubscriptionSubject.sink.add(active);

      return true;
    }
  }

  openSubscriptionsDialog() {
    neuDialog(
      padding: EdgeInsets.only(top: 30, left: 20, right: 20, bottom: 10),
      context: _context,
      child: StreamBuilder(
        stream: stream,
        builder: (BuildContext context, AsyncSnapshot<List<SubscriptionSelection>> data) {
          if(data.hasData) {
            return Container(
              width: double.infinity,
              child: Column(
                children: <Widget>[
                  Text("Mis suscripciones", style: Theme.of(context).textTheme.subtitle),
                  SizedBox(height: 30),
                  Wrap(
                    direction: Axis.horizontal,
                    runSpacing: 20,
                    children: data.data.asMap().entries.map((entry) {
                      final index = entry.key;
                      final item = entry.value;
                      return neuButton(
                        NeumorphicButton(
                          padding: EdgeInsets.symmetric(vertical: 0, horizontal: 2),
                          style: item.active ? neuStylePressed() : neuButtonStyle(),
                          boxShape: neuBoxShape(borderRadius: 16),
                          onClick: () async {
                            if(!item.active) {
                              await this.setActiveSubscription(index);
                            }
                            Navigator.pop(context);
                          },
                          child: ListTile(
                            contentPadding: EdgeInsets.all(10),
                            leading: ClipRRect(
                              borderRadius: BorderRadius.circular(8),
                              child: Container(
                                width: 50,
                                height: 50,
                                decoration: BoxDecoration(
                                  boxShadow: [BoxShadow(
                                    blurRadius: 10,
                                    spreadRadius: -5
                                  )]
                                ),
                                child: CachedNetworkImage(
                                  placeholder: (context, url) => CircularProgressIndicator(strokeWidth: 3, valueColor: new AlwaysStoppedAnimation<Color>(Theme.of(context).primaryColor)),
                                  imageUrl: item.company.logo_url,
                                  width: 50,
                                  height: 50,
                                  fit: BoxFit.cover
                                ),
                              ),
                            ),
                            title: Text("${item.box.city}, ${item.company.name}", maxLines: 1, overflow: TextOverflow.ellipsis,),
                            subtitle: Text("${item.role.name} - ${item.pricing.name}"),
                            trailing: Icon(Icons.navigate_next),
                          ),
                        ),
                        borderRadius: BorderRadius.circular(16)
                      );
                    }).toList(),
                  ),
                  SizedBox(height: 20),
                  FlatButton(
                    child: Text("Ver todas las suscripciones", style: Theme.of(context).textTheme.display1.copyWith(fontWeight: FontWeight.w500)),
                    onPressed: () { Navigator.pushNamed(context, 'my-subscriptions'); },
                  )
                ],
              ),
            );
          }
          else return Container(
            color: Colors.transparent,
            child: neuSkeletonCard(50,null)
          );
        },
      )
    );
  }

  void setContext(BuildContext context) {
    _context = context;
  }

}