import 'package:flutter/material.dart';
import 'main.dart';
import 'NewTask.dart';
import 'Data.dart';
import 'User.dart' as User;

class Tasks extends StatefulWidget {
  const Tasks({Key? key}) : super(key: key);

  @override
  _TasksState createState() => _TasksState();
}
class _TasksState extends State<Tasks> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    UpdateList();
  //  init(context);
  }

  var refreshSub;
  void init(BuildContext context) async{
    await Future.delayed(Duration(seconds: 1));
    refreshSub = User.refreshStream.stream.listen((value) {
      print("Streaming refresh : $value");
      if(value){
        //  dialogs.waiting(context, "Syncing");
        print("Opening progress dialog");
      }else{
        // dialogs.hide(context);
        print("Closing progress dialog");
      }
    });
  }

  @override void dispose() {
    // TODO: implement dispose
    super.dispose();
    refreshSub?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(

        floatingActionButton: FloatingActionButton.extended(
            onPressed: () {
              Navigator.of(context)
                  .push(MaterialPageRoute(builder: (context) => NewTask()))
                  .then((value) => UpdateList());
            },
            label: Text("New Task Type"),
            icon: Icon(Icons.add)),
        appBar: AppBar(
            title: Row(
              mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(children: [
              Icon(Icons.task, color: Theme.of(context).primaryColor),
              SizedBox(width: 10),
              Text('Task Types')
            ]),
            (selecting)?Row(children: [
              InkWell(onTap: (){
                DeleteSelectedTasks();
              }, child: Icon(Icons.delete,size: 30,)),
              SizedBox(width: 20,),
              InkWell(onTap: (){setState(() {
                selecting=false;
              });}, child: Icon(Icons.close,size: 30),)
            ]) : Container(),
          ],
        )),
        drawer: navDrawer(context, 3),
        body: Container(
            padding: EdgeInsets.all(10),
            child: SingleChildScrollView(
                child: Column(
              children: PrintTasks(),
            ))));
  }

  void UpdateList() async {

   // try{progressDialog.show(max:100, msg: 'Loading Task Types...');}catch(e){}
    await User.refreshUserData();
  //  hideProgressDialog();
    if(mounted)setState(() {});

   // try{progressDialog.update(value: 100);}catch(e){}
  }

  List<Widget> PrintTasks() {
    List<Widget> _tasks = [];
    print('Priting cats : ' + User.taskTypes.length.toString());
    User.taskTypes.forEach((element) {
      String name = element.name;
      if (element.cat == null) {
        print('Got some null cat : ${element.name}');
      } else {
        Color color = HexColor.fromHex(element.cat?.color ?? '#000000');
        bool productive = element.cat?.productive ?? true;
        Widget task = TaskCard(context, name, productive, color, element.cat?.name ?? 'n/a');
        _tasks.add(task);
      }
    });

    return _tasks;
  }

  bool selecting = false;
  Widget TaskCard(
      BuildContext context, String name, bool productive, Color color, String catName) {
    return Row(children: [
      // Container(),
      (selecting)
          ? Checkbox(
              value: selectedTasks.contains(name),
              onChanged: (value) {
                print('selected $name');
                OnItemSelected(name);
                setState(() {});
              })
          : Container(),
      Expanded(
        child: Column(children: [
          Card(

              // color: color,
            elevation:20,
              shadowColor: color,
              child: InkWell(
                  onTap: () {
                    //Open Respective Category
                    if(selecting){
                      OnItemSelected(name);
                    }
                    setState(() {

                    });
                  },
                  onLongPress: () {
                    print('gonna delete');
                    selecting = !selecting;
                    selectedTasks = [name];
                    setState(() {});

                  },
                  child: Container(
                      padding: EdgeInsets.all(10),
                      child: Column(
                        children: [
                          Row(
                              mainAxisSize: MainAxisSize.max,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(name,
                                    ),
                                // Icon(Icons.analytics, color: color, size: 20,),
                                Container(
                                    padding: EdgeInsets.symmetric(horizontal: 10),
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(10),
                                        color: (productive) ? Colors.green : Colors.red
                                    ),
                                    child:Text(catName)
                                )
                              ]),
                        ],
                      )))),
          Container(
              margin: EdgeInsets.fromLTRB(15, 0, 15, 10),
              height: 2,
              color: color)
        ]),
      ),
    ]);
  }

  void OnItemSelected(String name){
    if (!selectedTasks.contains(name)) {
      selectedTasks.add(name);
    } else {
      selectedTasks.remove(name);
    }
  }

  void DeleteSelectedTasks() async{
    selectedTasks.forEach((element) async {
      await User.UserOperations.deleteTask(element, bulk:true);
    });

    await Future.delayed(Duration(seconds: 2));
    await User.UserOperations.executeQueries();
    selectedTasks=[];
    selecting=false;
    setState(() {
    });

  }

}

List<String> selectedTasks = [];
