/// Flutter code sample for BottomNavigationBar

// This example shows a [BottomNavigationBar] as it is used within a [Scaffold]
// widget. The [BottomNavigationBar] has four [BottomNavigationBarItem]
// widgets, which means it defaults to [BottomNavigationBarType.shifting], and
// the [currentIndex] is set to index 0. The selected item is amber in color.
// With each [BottomNavigationBarItem] widget, backgroundColor property is
// also defined, which changes the background color of [BottomNavigationBar],
// when that item is selected. The `_onItemTapped` function changes the
// selected item's index and displays a corresponding message in the center of
// the [Scaffold].

import 'package:flutter/material.dart';
import 'package:jubo/control/authService.dart';
import 'package:jubo/event.dart';
import 'package:jubo/model/person.dart';
import 'package:jubo/orderArtist.dart';
import 'package:jubo/orderCustomer.dart';
import 'package:jubo/ui/loading.dart';
import 'package:jubo/ui/profile.dart';
import 'splash.dart';
import 'event.dart';
import 'model/modelEvent_Artist.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'util/params.dart';
import 'dart:convert';

class Event_Artist extends StatefulWidget {
  Event_Artist(
      {this.idEvent,
      this.person_spot_name,
      this.date_event,
      this.note,
      this.person_spot_id,
      this.person_type,
      this.person_id});
  final int idEvent;
  final String person_spot_name;
  final int person_spot_id;
  final String date_event;
  final String note;
  final String person_type;
  final int person_id;
  @override
  Event_ArtistState createState() => Event_ArtistState();
}

class Event_ArtistState extends State<Event_Artist> {
  bool loading = false;

  static BuildContext contextGlobal;
  List<ModelEvent_Artist> listEvents;

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

  void _onItemTapped(int index) {
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    contextGlobal = context;
    return Scaffold(
        appBar: PreferredSize(
            preferredSize: Size.fromHeight(60.0),
            child: AppBar(
                leading: ElevatedButton(
                  style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all<Color>(
                          Color.fromRGBO(68, 49, 122, 1.0))),
                  child: Icon(
                    Icons.arrow_back,
                    color: Color.fromRGBO(103, 197, 180, 1.0),
                  ),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                ),
                centerTitle: true,
                title: Image.asset(
                  'assets/images/Jubo_Logo_White.png',
                  width: 200,
                ),
                backgroundColor: Color.fromRGBO(68, 49, 122, 1.0))),
        body: Container(
          color: COLOR_TERTIARY,
          child: Column(
            mainAxisSize: MainAxisSize.max,
            children: [
              Container(
                color: COLOR_LINE_1,
                width: double.infinity,
                height: 100,
                child: Row(
                  children: [
                    Container(
                      color: COLOR_PRIMARY,
                      width: 100,
                      height: 100,
                      child: Image(
                        fit: BoxFit.fill,
                        image: NetworkImage(
                            "$urlPrincipal/ws_jubo/service/v1/person/photo/${widget.person_spot_id}"),
                      ),
                    ),
                    Expanded(
                      child: ListTile(
                        title: Text(
                          this.widget.person_spot_name,
                          style: TextStyle(
                              fontSize: 20,
                              fontWeight: FontWeight.bold,
                              color: COLOR_PRIMARY),
                        ),
                        subtitle: Text(
                          this.widget.note,
                          style: TextStyle(
                            fontSize: 15,
                            color: COLOR_TERTIARY,
                          ),
                        ),
                        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(5),
                            color: COLOR_PRIMARY,
                            child: Text(
                              DateFormat("dd/MM/yyyy").format(
                                  DateTime.parse(this.widget.date_event)),
                              style: TextStyle(
                                  color: COLOR_LINE_1,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(
                child: loading
                    ? Loading()
                    : Container(
                        color: COLOR_TERTIARY,
                        child: eventsListView(listEvents),
                      ),
                /*
                FutureBuilder<List<ModelEvent_Artist>>(
                  future: getEvents(),
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      List<ModelEvent_Artist> data = snapshot.data;
                      return eventsListView(data);
                    } else if (snapshot.hasError) {
                      return Text("${snapshot.error}");
                    }
                    return CircularProgressIndicator();
                  },
                ),*/
              ),
            ],
          ),
        ));
  }

  Future<List<ModelEvent_Artist>> getEvents() async {
    setState(() {
      loading = true;
    });
    await Future.delayed(Duration(seconds: 1));
    final response = await http.get(
        "$urlPrincipal/ws_jubo/service/v1/event_artist/all?id_event=${widget.idEvent.toString()}",
        headers: {"Accept": "application/json"});

    if (response.statusCode == 200) {
      List jsonResponse = json.decode(response.body)['data'];

      setState(() {
        loading = false;
        listEvents = jsonResponse
            .map((job) => new ModelEvent_Artist.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 _card(data[index].id, data[index].person_artist_name,
              data[index].note, data[index].person_artist_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_artist_name, note, person_artist_id) {

    Navigator.push(
        contextGlobal,
        MaterialPageRoute(
            builder: (context) => widget.person_type != "Customer"
                ? OrderArtist(
                    idEvent: widget.idEvent,
                    person_artist_name: person_artist_name,
                    note: note,
                    person_artist_id: person_artist_id,
                    person_type: widget.person_type,
                  )
                : OrderCustomer(
                    idEvent_Artist: id,
                    id_event: widget.idEvent,
                    person_artist_name: person_artist_name,
                    person_artist_id: person_artist_id,
                    note: note,
                    person_customer_id: widget.person_id,
                  )));
  }

  Card _card(int id, String title, String subtitle, 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.fromRGBO(103, 197, 180, 1.0),
                  child: Text(
                    DateFormat("dd/MM/yyyy").format(DateTime.parse(subtitle2)),
                    style: TextStyle(
                        color: Color.fromRGBO(68, 49, 122, 1.0),
                        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, subtitle, icon);
          }));
}
