import 'dart:async';

/// 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/event.dart';
import 'package:jubo/model/modelEvent_Artist.dart';
import 'package:jubo/ui/loading.dart';
import 'splash.dart';
import 'event.dart';
import 'model/modelOrder.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'util/params.dart';
import 'dart:convert';
import 'formOrder.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:jubo/control/genericService.dart' as generic;

class OrderArtist extends StatefulWidget {
  OrderArtist(
      {this.idEvent,
      this.person_artist_name,
      this.person_artist_id,
      this.note,
      this.person_type});
  final int idEvent;
  final String person_artist_name;
  final int person_artist_id;
  final String note;
  final String person_type;

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

class OrderState extends State<OrderArtist> {
  static BuildContext contextGlobal;
  static Timer _timer;
  bool loading = false;
  List<ModelOrder> listOrder;
  bool autoRefresh;
  double totalOrder;

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

  void _setAutoRefresh() {
    setState(() {
      if (!autoRefresh) {
        autoRefresh = true;
        _timer = Timer.periodic(Duration(seconds: 20), (timer) {
          getOrders();
        });
      } else {
        try {
          autoRefresh = false;
          _timer.cancel();
        } catch (e) {}
      }
    });
  }

  @override
  void dispose() {
    try {
      autoRefresh = false;
      _timer.cancel();
    } catch (e) {}
    super.dispose();
  }

  void initState() {
    super.initState();
    autoRefresh = false;
    getOrders();
  }

  @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_artist_id}"),
                  ),
                ),
                Expanded(
                  child: ListTile(
                    dense: true,
                    title: Text(
                      this.widget.person_artist_name,
                      style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                          color: COLOR_PRIMARY),
                    ),
                    subtitle: Text(
                      this.widget.note,
                      style: TextStyle(
                        fontSize: 12,
                        color: COLOR_TERTIARY,
                      ),
                    ),
                  ),
                ),
                Column(
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Center(
                          child: Text(
                            "Live",
                            style: TextStyle(
                              fontSize: 16,
                              color: COLOR_PRIMARY,
                            ),
                          ),
                        ),
                        Center(
                          child: IconButton(
                            icon: autoRefresh
                                ? Icon(Icons.toggle_on)
                                : Icon(Icons.toggle_off),
                            onPressed: _setAutoRefresh,
                            color: autoRefresh
                                ? Color.fromRGBO(47, 99, 41, 1.0)
                                : Color.fromRGBO(109, 40, 40, 1.0),
                            iconSize: 36,
                          ),
                        ),
                      ],
                    ),
                    //Container(color: COLOR_PRIMARY,height: 2,width: 80,),
                    Expanded(
                      child: Container(
                        padding: EdgeInsets.all(5),
                        child: ClipRRect(
                          borderRadius: BorderRadius.only(
                              bottomLeft: Radius.circular(5),
                              bottomRight: Radius.circular(5),
                              topLeft: Radius.circular(5),
                              topRight: Radius.circular(5)),
                          child: widget.person_type != "Spot"
                              ? Container(
                                  padding: EdgeInsets.all(5),
                                  color: Color.fromRGBO(47, 99, 41, 1.0),
                                  width: 70,
                                  child: Center(
                                    child: Text(
                                      NumberFormat.currency(
                                              locale: 'pt_BR',
                                              decimalDigits: 2,
                                              customPattern: '#,###.#')
                                          .format(loading ? 0.00 : totalOrder),
                                      style: TextStyle(
                                          color: COLOR_FONT_1,
                                          fontWeight: FontWeight.bold),
                                    ),
                                  ),
                                )
                              : Container(),
                        ),
                      ),
                    )
                  ],
                ),
              ],
            ),
          ),
          Expanded(
            child: loading
                ? Loading()
                : RefreshIndicator(
                    onRefresh: () => getOrders(),
                    child: Container(
                      color: COLOR_TERTIARY,
                      child: ordersListView(listOrder),
                      /*FutureBuilder<List<ModelOrder>>(
                  future: getOrders(),
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      List<ModelOrder> data = snapshot.data;
                      return ordersListView(data);
                    } else if (snapshot.hasError) {
                      return Text("${snapshot.error}");
                    }
                    return CircularProgressIndicator();
                  },
                ),*/
                    ),
                  ),
          )
        ]),
      ),

      /*persistentFooterButtons: <Widget>[
        IconButton(icon: Icon(Icons.insert_emoticon),onPressed: () {}),
      ],*/
    );
  }

  Future<void> getOrders() async {
    setState(() {
      loading = true;
      totalOrder = 0.0;
    });

    await Future.delayed(Duration(seconds: 1));
    List<ModelOrder> list;
    List<ModelOrder> filteredList = [];
    double valueOrder = 0.0;
    final response = await http.get(
        "$urlPrincipal/ws_jubo/service/v1/order/all?id_event=${widget.idEvent.toString()}&"
        "id_person_artist=${widget.person_artist_id.toString()}",
        headers: {"Accept": "application/json"});

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

      if (widget.person_type != "Spot") {
        for (var item in list) {
          if (item.status == 'Pending') {
            filteredList.add(item);
          } else if (item.status == 'Finalized') {
            valueOrder = valueOrder + item.value;
          }
        }
      } else {
        filteredList.addAll(list);
      }

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

  Future<void> statusOrder(int id, String status) async {
    setState(() {
      loading = true;
    });
    await Future.delayed(Duration(seconds: 1));

    String method = "/ws_jubo/service/v1/statusOrder";

    http.Response result =
        await generic.requestPost({'id': id, 'status': status}, method, "");

    Map<String, dynamic> body = jsonDecode(result.body);

    if (result.statusCode == 200 && body['error'] != true) {
      await getOrders();
      //return jsonResponse.map((job) => new ModelOrder.fromJson(job)).toList();
    } else {
      setState(() {
        loading = false;
      });
      throw Exception('Failed to load jobs from API');
    }
  }

  Container eventsListView(data) {
    return Container(
      child: Text(data.person_artist_name),
    );
  }

  ListView ordersListView(data) {
    return ListView.builder(
        itemCount: data.length,
        padding: EdgeInsets.fromLTRB(8, 8, 8, 8),
        itemBuilder: (context, index) {
          return _card(
              data[index].id,
              data[index].value,
              data[index].text_artist,
              data[index].text_music,
              data[index].person_customer_name,
              data[index].person_customer_id,
              data[index].note,
              Icons.assignment_ind_rounded,
              data[index].status);
        });
  }

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

  clickViewImage(int image) {
    showDialog(
        context: contextGlobal,
        builder: (contextGlobal) {
          return Container(
            width: 200,
            height: 200,
            child: Image(
              image: NetworkImage(
                  "$urlPrincipal/ws_jubo/service/v1/person/photo/$image"),
            ),
          );
        });
  }

  String removeAcento(String text) {
    text = text.toLowerCase();
    text = text.replaceAll(new RegExp(r'[ÁÀÂÃ]', caseSensitive: false), 'a');
    text = text.replaceAll(new RegExp(r'[ÉÈÊ]', caseSensitive: false), 'e');
    text = text.replaceAll(new RegExp(r'[ÍÌÎ]', caseSensitive: false), 'i');
    text = text.replaceAll(new RegExp(r'[ÓÒÔÕ]', caseSensitive: false), 'o');
    text = text.replaceAll(new RegExp(r'[ÚÙÛ]', caseSensitive: false), 'u');
    text = text.replaceAll(new RegExp(r'[Ç]', caseSensitive: false), 'c');
    text = text.replaceAll(new RegExp(r"\s+\b|\b\s"), '-');
    return text;
  }

  abrirUrl(url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

  void clickEvent(id, text_artist, text_music) {
    setState(() {
      try {
        autoRefresh = false;
        _timer.cancel();
      } catch (e) {}
    });
    if (widget.person_type != "Spot") {
      showDialog(
          context: contextGlobal,
          builder: (context) {
            return Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  MaterialButton(
                    color: Colors.orange,
                    padding: EdgeInsets.all(20),
                    elevation: 5,
                    onPressed: () {
                      if (text_artist == '') {
                        abrirUrl('https://m.cifraclub.com.br/?q=' +
                            removeAcento(text_music));
                      } else {
                        abrirUrl('https://m.cifraclub.com.br/' +
                            removeAcento(text_artist) +
                            '/' +
                            removeAcento(text_music));
                      }
                    },
                    child: Icon(
                      Icons.music_note_rounded,
                      color: Colors.white,
                    ),
                  ),
                  MaterialButton(
                    color: Colors.green,
                    padding: EdgeInsets.all(20),
                    onPressed: () {
                      statusOrder(id, "Finalized");
                      Navigator.pop(context);
                    },
                    child: Icon(
                      Icons.mic,
                      color: Colors.white,
                    ),
                  ),
                  MaterialButton(
                    color: Colors.redAccent,
                    padding: EdgeInsets.all(20),
                    onPressed: () {
                      statusOrder(id, "Canceled");
                      Navigator.pop(context);
                    },
                    child: Icon(
                      Icons.mic_off,
                      color: Colors.white,
                    ),
                  )
                ]);
          });
    }
  }

  /*
   new Card(
                child: new Container(
                  padding: new EdgeInsets.all(32.0),
                  child: new Column(
                    children: <Widget>[
                      new Text('Hello World'),
                      new Text('How are you?')
                    ],
                  ),
                ),
              ),
   */

  Card _card(
          int id,
          double value,
          String text_artist,
          String text_music,
          String person_customer_name,
          int person_customer_id,
          String note,
          IconData icon,
          String status) =>
      Card(
          color: status == "Pending"
              ? Color.fromRGBO(68, 49, 122, 1.0)
              : status == "Finalized"
                  ? Color.fromRGBO(68, 49, 122, 0.5450980392156862)
                  : Color.fromRGBO(99, 41, 64, 1.0),
          borderOnForeground: true,
          child: ListTile(
            enabled: status == "Pending",
            dense: true,
            onTap: () {
              clickEvent(id, text_artist, text_music);
            },
            shape: null,
            title: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    text_artist == ""
                        ? Text("")
                        : Icon(
                            Icons.person,
                            size: 14,
                            color: status == "Pending"
                                ? COLOR_FONT_1
                                : COLOR_FONT_1_DISABLED,
                          ),
                    Text(" " + text_artist,
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                          color: status == "Pending"
                              ? COLOR_FONT_1
                              : COLOR_FONT_1_DISABLED,
                        )),
                  ],
                ),
                SizedBox(
                  height: 6,
                ),
                Row(
                  children: [
                    text_music == ""
                        ? Text("")
                        : Icon(
                            Icons.music_note,
                            size: 14,
                            color: status == "Pending"
                                ? COLOR_FONT_1
                                : COLOR_FONT_1_DISABLED,
                          ),
                    Text(" " + text_music,
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                          color: status == "Pending"
                              ? COLOR_FONT_1
                              : COLOR_FONT_1_DISABLED,
                        )),
                  ],
                ),
                SizedBox(
                  height: 10,
                ),
              ],
            ),
            subtitle: Text(
              note,
              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(4),
                color: Color.fromRGBO(103, 197, 180, 1.0),
                child: Text(
                  NumberFormat.currency(
                          locale: 'pt_BR',
                          decimalDigits: 2,
                          customPattern: '#,###.#')
                      .format(value.toDouble()),
                  style: TextStyle(
                      color: Color.fromRGBO(68, 49, 122, 1.0),
                      fontWeight: FontWeight.bold),
                ),
              ),
            ),
            isThreeLine: true,
            leading: CircleAvatar(
              backgroundImage: NetworkImage(
                  "$urlPrincipal/ws_jubo/service/v1/person/photo/$person_customer_id"),
            ),
          ));
}
