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

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:jubo/control/authService.dart';
import 'package:jubo/model/person.dart';
import 'package:jubo/model/modelCreditCard.dart';
import 'package:jubo/orderArtist.dart';
import 'package:jubo/ui/formCreditCard.dart';
import 'package:jubo/ui/loading.dart';
import 'package:intl/intl.dart';
import '../event_Artist.dart';
import 'package:flutter_credit_card/flutter_credit_card.dart';
import '../util/params.dart';

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

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

class CreditCards_State extends State<CreditCards> {
  bool loading_person = false;
  ModelPerson person;
  bool loading = false;
  List<ModelCreditCard> listCreditCards;

  void initState() {
    super.initState();
    loadPerson();
  }

  static BuildContext contextGlobal;

  void loadPerson() async {
    setState(() => loading_person = true);
    AuthenticationService auth = new AuthenticationService();
    //await Future.delayed(Duration(seconds: 1));
    ModelPerson loggedPerson = await auth.getPerson();
    setState(() {
      person = loggedPerson;
      loading_person = false;
    });
    await getCreditCards();
  }

  @override
  Widget build(BuildContext context) {
    contextGlobal = context;
    return (loading || loading_person)
        ? Loading()
        : Scaffold(
            appBar: AppBar(
              elevation: 5.0,
              backgroundColor: COLOR_PRIMARY,
              title: Text("Meus Cartões"),
              leading: TextButton(
                child: Icon(
                  Icons.arrow_back,
                  size: 30.0,
                  color: Colors.white,
                ),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
            ),
            body: Container(
              width: double.infinity,
              color: COLOR_TERTIARY,
              child: listCreditCards.length == 0
                  ? Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.cloud_off_outlined),
                        Text("Sem Dados")
                      ],
                    )
                  : eventsListView(listCreditCards),

              /*FutureBuilder<List<ModelEvent>>(
        future: getEvents(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            List<ModelEvent> data = snapshot.data;
            return eventsListView(data);
          } else if (snapshot.hasError) {
            return Text("${snapshot.error}");
          }
          return CircularProgressIndicator();
        },
      ),*/
            ),
            floatingActionButton: FloatingActionButton(
              child: Icon(Icons.add),
              backgroundColor: COLOR_PRIMARY,
              onPressed: () {
                Navigator.push(
                    contextGlobal,
                    MaterialPageRoute(
                        builder: (context) => FormCreditCard(
                              person_id: person.id,
                            ))).then((value) {
                  if (value == null) {
                    value = true;
                  }
                  bool reload = value;
                  if (reload) {
                    getCreditCards();
                  }
                });
              },
            ),
            floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
          );
  }

  Future<void> getCreditCards() async {
    setState(() {
      loading = true;
    });
    //await Future.delayed(Duration(seconds: 1));
    String condition = "?id_person=${person.id}";
    final response = await http.get(
        "$urlPrincipal/ws_jubo/service/v1/paymeth$condition",
        headers: {"Accept": "application/json"});
    if (response.statusCode == 200) {
      //print(response.body);
      List jsonResponse = json.decode(response.body)['data'];
      //List jsonResponse = json.decode(response.body);
      setState(() {
        loading = false;
        listCreditCards = jsonResponse
            .map((job) => new ModelCreditCard.fromJson(job))
            .toList();
      });
    } else {
      setState(() {
        loading = false;
      });
      throw Exception('Failed to load jobs from API');
    }
  }

  ListView eventsListView(data) {
    return ListView.builder(
        itemCount: data.length,
        padding: EdgeInsets.fromLTRB(8, 8, 8, 8),
        itemBuilder: (context, index) {
          return _creditCard(data[index]);
        });
  }

  void clickAlert(id) {
    showDialog(
        context: contextGlobal,
        builder: (contextGlobal) {
          return AlertDialog(
            title: new Text("Evento"),
            content: new Text("Selecionado: " + id.toString()),
          );
        });
  }

  void clickEvent(id, person_spot_name, date_event, note, person_spot_id) {
    if (person.type == "Artist") {
      Navigator.push(
          contextGlobal,
          MaterialPageRoute(
              builder: (context) => OrderArtist(
                  idEvent: id,
                  person_artist_name: person.name,
                  note: note,
                  person_artist_id: person.id)));
    } else {
      Navigator.push(
          contextGlobal,
          MaterialPageRoute(
              builder: (context) => Event_Artist(
                    idEvent: id,
                    person_spot_name: person_spot_name,
                    date_event: date_event,
                    note: note,
                    person_spot_id: person_spot_id,
                    person_id: person.id,
                    person_type: person.type,
                  )));
    }
  }

  Container _creditCard(ModelCreditCard data) => Container(
        height: 220,
        alignment: AlignmentDirectional.bottomStart,
        margin: EdgeInsets.only(bottom: 10),
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/CreditCardBackground.png'),
            fit: BoxFit.cover,
          ),
          color: Color.fromRGBO(68, 49, 122, 1.0),
          borderRadius: BorderRadius.circular(10),
          boxShadow: [
            BoxShadow(
                color: Color.fromRGBO(57, 45, 92, 1.0),
                spreadRadius: 0,
                blurRadius: 10),
          ],
        ),
        child: Card(
            color: Colors.transparent,
            borderOnForeground: true,
            elevation: 0,
            child: Column(
              children: [
                SizedBox(
                    height: 130,
                    child: Text(data.description,
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                          color: COLOR_FONT_1,
                        ))),
                ListTile(
                    shape: null,
                    title: Text(data.display_number,
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                          color: COLOR_FONT_1,
                        )),
                    subtitle: Text(
                      data.holder_name,
                      style: TextStyle(
                        color: COLOR_LINE_1,
                      ),
                    ),
                    trailing: Text(
                      "${data.month}/${data.year}",
                      style: TextStyle(
                          color: COLOR_LINE_1, fontWeight: FontWeight.bold),
                    ),
                    isThreeLine: true,
                    //leading: Icon(Icons.credit_card,color: COLOR_LINE_1,),
                    onTap: () {
                      //clickEvent(id, title, subtitle2, subtitle, icon);
                    }),
              ],
            )),
      );
}
