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/model/person.dart';
import 'package:jubo/orderArtist.dart';
import 'package:jubo/ui/loading.dart';
import 'model/modelEvent.dart';
import 'package:intl/intl.dart';
import 'event_Artist.dart';
import 'util/params.dart';
import 'ui/formEvent.dart';

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

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

class Event_State extends State<Event> {
  bool loading_person = false;
  ModelPerson person;
  bool loading = false;
  List<ModelEvent> listEvents;
  String dataFiltro;

  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();
    //Image c = await auth.getPhoto();
    setState(() {
      /*current = Image.asset(
        'assets/images/photo_1.jb',
        fit: BoxFit.cover,
      );*/
      // id = loggedPerson.id;
      // password = loggedPerson.password;
      // photo = loggedPerson.photo;
      //name = loggedPerson.name;
      //email = loggedPerson.email;
      //inserted_date = loggedPerson.inserted_date;
      person = loggedPerson;
      dataFiltro = DateFormat('yyyy-MM-dd').format(DateTime.now());

      //birth = loggedPerson.birth;
      //birthSql =
      //    DateFormat('yyyy-MM-dd').format(DateTime.parse((loggedPerson.birth)));
      // birthController.text =
      //   DateFormat('dd/MM/yyyy').format(DateTime.parse((loggedPerson.birth)));
      //current = c;
      loading_person = false;
    });
    await getEvents();
  }

  @override
  Widget build(BuildContext context) {
    contextGlobal = context;
    return (loading || loading_person)
        ? Loading()
        : Column(children: [
            SizedBox(height: 4),
            Container(
              height: 45,
              width: double.infinity,
              padding: EdgeInsets.only(left: 20),
              alignment: Alignment.centerLeft,
              child: Row(
                children: [
                  Text(
                    "Eventos do dia - ",
                    style: TextStyle(
                      color: COLOR_FONT_1,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  ClipRRect(
                    borderRadius: BorderRadius.only(
                        bottomLeft: Radius.circular(5),
                        bottomRight: Radius.circular(5),
                        topLeft: Radius.circular(5),
                        topRight: Radius.circular(5)),
                    child: GestureDetector(
                      onTap: () {
                        _selectDate();
                        FocusScope.of(context).requestFocus(new FocusNode());
                      },
                      child: Container(
                        padding: EdgeInsets.all(2),
                        color: COLOR_LINE_1,
                        child: Text(
                          DateFormat("dd/MM/yyyy")
                              .format(DateTime.parse(dataFiltro)),
                          style: TextStyle(
                              color: COLOR_PRIMARY,
                              fontWeight: FontWeight.bold),
                        ),
                      ),
                    ),
                  ),
                  (person.type == "Spot" || person.type == "Artist")
                      ? Expanded(
                          child: Container(
                            padding: EdgeInsets.only(right: 15, left: 15),
                            child: ElevatedButton(
                              onPressed: () => goForm(),
                              style: ElevatedButton.styleFrom(
                                primary: Color.fromRGBO(47, 99, 41, 1.0),
                                padding: EdgeInsets.only(top: 5, bottom: 5),
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(5),
                                    side: BorderSide(color: COLOR_PRIMARY)),
                              ),
                              child: Text(
                                person.type == "Spot" ? ' + Novo Evento' : ' Encontrar Evento',
                                style: TextStyle(
                                  //fontSize: 12,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.white,
                                ),
                              ),
                            ),
                          ),
                        )
                      : SizedBox()
                ],
              ),
              decoration: BoxDecoration(
                color: COLOR_PRIMARY,
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(0), topRight: Radius.circular(0)),
              ),
            ),
            Expanded(
              child: Container(
                color: COLOR_TERTIARY,
                child: listEvents.length == 0
                    ? Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(Icons.cloud_off_outlined),
                          Text("Sem Dados")
                        ],
                      )
                    : eventsListView(listEvents),

                /*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();
            },
          ),*/
              ),
            ),
          ]);
  }

  Future<List<ModelEvent>> getEvents() async {
    setState(() {
      loading = true;
    });
    await Future.delayed(Duration(seconds: 1));
    String condition = "?date_event=${dataFiltro}";

    condition += person.type == "Artist"
        ? "&id_person_artist=${person.id}"
        : person.type == "Spot"
            ? "&id_person_spot=${person.id}"
            : "";

    final response = await http.get(
        "$urlPrincipal/ws_jubo/service/v1/event/all$condition",
        headers: {"Accept": "application/json"});

    if (response.statusCode == 200) {
      List jsonResponse = json.decode(response.body)['data'];
      setState(() {
        loading = false;
        listEvents =
            jsonResponse.map((job) => new ModelEvent.fromJson(job)).toList();
      });
    } else {
      setState(() {
        loading = false;
      });
      throw Exception('Failed to load jobs from API');
    }
  }

  Future _selectDate() async {
    DateTime picked = await showDatePicker(
        context: context,
        locale: Locale("pt", "BR"),
        initialDate: DateTime.now(),
        firstDate: new DateTime(1900),
        lastDate: new DateTime(2030));
    if (picked != null)
      setState(() => {
            dataFiltro = DateFormat('yyyy-MM-dd').format(picked),

            //birthController.text = DateFormat('dd/MM/yyyy').format(picked)
          });
    await getEvents();
  }

  ListView eventsListView(data) {
    return ListView.builder(
        itemCount: data.length,
        padding: EdgeInsets.fromLTRB(8, 8, 8, 8),
        itemBuilder: (context, index) {
          return _card(
              data[index].id,
              data[index].person_spot_name,
              data[index].note,
              data[index].date_event,
              data[index].person_spot_id);
        });
  }

  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,
                  )));
    }
  }

  void goForm() {
    //print(idOrder);

    Navigator.push(
        contextGlobal,
        MaterialPageRoute(
            builder: (context) => FormEvent(id_person_spot: person.id,
                ))).then((value) async {
      bool reload = value;
      if (reload) {
        await getEvents();
      }
    });
  }

  Card _card(int id, String title, String subtitle, String subtitle2, int icon) => Card(
      color: Color.fromRGBO(68, 49, 122, 1.0),
      borderOnForeground: true,
      child: ListTile(
          shape: null,
          title: Text(title,
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 16,
                color: COLOR_FONT_1,
              )),
          subtitle: Text(
            subtitle,
            style: TextStyle(
              color: COLOR_LINE_1,
            ),
          ),
          /*trailing: ClipRRect(
                borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(5),
                    bottomRight: Radius.circular(5),
                    topLeft: Radius.circular(5),
                    topRight: Radius.circular(5)),
                child: Container(
                  padding: EdgeInsets.all(2),
                  color: COLOR_LINE_1,
                  child: Text(
                    DateFormat("dd/MM/yyyy").format(DateTime.parse(subtitle2)),
                    style: TextStyle(
                        color: COLOR_PRIMARY, fontWeight: FontWeight.bold),
                  ),
                ),
              ),*/

          /*
              Text(
                DateFormat("dd/MM/yyyy").format(DateTime.parse(subtitle2)),
                style: TextStyle(
                    backgroundColor: Color.fromRGBO(103, 197, 180, 1.0),
                    b
                    color: Color.fromRGBO(68, 49, 122, 1.0),
                    fontWeight: FontWeight.bold),
              ),
               */
          isThreeLine: true,
          leading: CircleAvatar(
            backgroundImage: NetworkImage(
                "$urlPrincipal/ws_jubo/service/v1/person/photo/$icon"),
          ), //
          onTap: () {
            clickEvent(id, title, subtitle2, subtitle, icon);
          }));
}
