import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:jubo/control/authService.dart';
import 'package:jubo/login.dart';
import 'package:jubo/model/modelWallet.dart';
import 'package:jubo/model/person.dart';
import 'package:jubo/ui/changePassword.dart';
import 'package:jubo/ui/formWallet.dart';
import 'package:jubo/ui/loading.dart';
import 'package:jubo/ui/profile.dart';
import '../model/modelEvent.dart';
import 'package:intl/intl.dart';
import '../event_Artist.dart';
import '../util/params.dart';

class Wallet extends StatefulWidget {
  const Wallet({key, BuildContext context}) : super(key: key);

  static BuildContext contextGlobal;
  @override
  Wallet_State createState() => Wallet_State();
}

class Wallet_State extends State<Wallet> {
  bool loading = false;
  List<ModelWallet> listWallets;
  ModelPerson loggedPerson;
  double totalActual;
  void initState() {
    super.initState();
    getWallet();
  }

  Future<void> getWallet() async {
    setState(() {
      loading = true;
      totalActual = 0.0;
    });

    await Future.delayed(Duration(seconds: 1));

    AuthenticationService auth = new AuthenticationService();

    loggedPerson = await auth.getPerson();

    double valueWallet = 0.0;
    final response = await http.get(
        "$urlPrincipal/ws_jubo/service/v1/wallet?"
        "id_person=${loggedPerson.id}&size=20",
        headers: {"Accept": "application/json"});

    if (response.statusCode == 200) {
      List jsonResponse = json.decode(response.body)['data'];
      listWallets =
          jsonResponse.map((job) => new ModelWallet.fromJson(job)).toList();

      for (var item in listWallets) {
        if (item.cashIn > 0.00) {
          valueWallet = valueWallet + item.cashIn;
        } else if (item.cashOut > 0.00) {
          valueWallet = valueWallet - item.cashOut;
        }
      }

      setState(() {
        loading = false;
        totalActual = valueWallet;
      });
      //return jsonResponse.map((job) => new ModelOrder.fromJson(job)).toList();
    } else {
      setState(() {
        loading = false;
      });
      throw Exception('Failed to load jobs from API');
    }
  }

  ListView ordersListView(data) {
    return ListView.separated(
        separatorBuilder: (BuildContext context, int index) => Divider(
              color: COLOR_TERTIARY,
              height: 1,
            ),
        itemCount: data.length,
        padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
        itemBuilder: (context, index) {
          return _card("Pedido", data[index].dateWallet, data[index].cashIn,
              data[index].cashOut);
        });
  }

  ListTile _card(
          String title, String subtitle, double cash_in, double cash_out) =>
      ListTile(
        dense: false,
        tileColor: COLOR_FONT_1,
        leading: Icon(
          cash_in > 0.00 ? Icons.monetization_on_outlined : Icons.payment,
          color: COLOR_PRIMARY,
        ),
        subtitle: Text(
          DateFormat('dd/MM/yyyy').format(DateTime.parse(subtitle)),
          style: TextStyle(
            color: COLOR_FONT_2,
          ),
        ),
        title: Text(
          cash_in > 0.00 ? "Crédito" : "Pedido de Música",
          style: TextStyle(
            color: COLOR_PRIMARY,
            fontWeight: FontWeight.w600,
          ),
        ),
        /*onTap: () {
          Navigator.pushReplacement(
              context, MaterialPageRoute(builder: (context) => Profile()));
        },*/
        trailing: Text(
          NumberFormat.currency(
                  locale: 'pt_BR', decimalDigits: 2, customPattern: '#,###.#')
              .format(cash_in > 0.00 ? cash_in : cash_out),
          style: TextStyle(
            color: cash_out > 0.00
                ? Color.fromRGBO(120, 35, 35, 1.0)
                : Color.fromRGBO(37, 111, 40, 1.0),
            fontWeight: FontWeight.bold,
          ),
        ),
      );

  @override
  Widget build(BuildContext context) {
    return loading
        ? Loading()
        : Scaffold(
//      color: COLOR_TERTIARY,
            body: Container(
              color: COLOR_TERTIARY,
              child: Column(
                children: [
                  SizedBox(height: 4),
                  /*Center(
                      child: Text(
                    NumberFormat.currency(
                            locale: 'pt_BR',
                            decimalDigits: 2,
                            customPattern: '#,###.#')
                        .format(loading ? 0.00 : totalActual),
                    style: TextStyle(
                        color: COLOR_FONT_1,
                        fontSize: 48,
                        fontWeight: FontWeight.bold),
                  )),
                  SizedBox(height: 15),
                  totalActual > 0.00
                      ? ElevatedButton(
                          onPressed: () {
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => FormWallet(
                                          type: loggedPerson.type,
                                        ))).then((value) {
                              bool reload = value;
                              if (reload) {
                                getWallet();
                              }
                            });
                          },
                          style: ElevatedButton.styleFrom(
                            primary: loggedPerson.type == 'Customer'
                                ? Color.fromRGBO(47, 99, 41, 1.0)
                                : Color.fromRGBO(51, 51, 156, 1.0),
                            padding: EdgeInsets.only(
                                top: 16, bottom: 16, left: 16, right: 16),
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(5),
                                side: BorderSide(color: COLOR_PRIMARY)),
                          ),
                          child: Text(
                            loggedPerson.type == 'Customer'
                                ? ' + Comprar Crédito '
                                : ' - Resgatar Saldo ',
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              color: Colors.white,
                            ),
                          ),
                        )
                      : SizedBox(height: 0),
                  totalActual > 0.00
                      ? SizedBox(height: 15)
                      : SizedBox(height: 0),*/
                  Container(
                    height: 45,
                    width: double.infinity,
                    padding: EdgeInsets.only(left: 20),
                    alignment: Alignment.centerLeft,
                    child: Text(
                      "Ultimos lançamentos",
                      style: TextStyle(
                        color: COLOR_FONT_1,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    decoration: BoxDecoration(
                      color: COLOR_PRIMARY,
                      borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(0),
                          topRight: Radius.circular(0)),
                    ),
                  ),
                  /*Container(
                      width: double.infinity,
                      height: 45,
                      color: COLOR_FONT_1,
                      padding: EdgeInsets.only(left: 20),
                      child: Text(
                        "Ultimos lançamentos",
                        style: TextStyle(
                          color: COLOR_TERTIARY,
                          fontWeight: FontWeight.bold,
                        ),
                      )),*/
                  Expanded(
                    child: ordersListView(listWallets),
                  ),
                ],
              ),
            ),
          );
  }
}
