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



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

  @override
  _ActivitiesState createState() => _ActivitiesState();
}
late ProgressDialog progressDialog;
class _ActivitiesState extends State<Activities> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    UpdateList();
  }

  @override
  Widget build(BuildContext context) {
    progressDialog=ProgressDialog(context: context);
    return Scaffold(

        floatingActionButton: FloatingActionButton.extended(
            onPressed: () {
              Navigator.of(context)
                  .push(MaterialPageRoute(builder: (context) => NewTask()))
                  .then((value) => UpdateList());
            },
            label: Text("New Activity"),
            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('Activities')
            ]),
            (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 {
    if(progressDialog != null){progressDialog.show(max:100,msg: 'Loading Task Types');}
    await User.updateTasksList();
    setState(() {});
    if(progressDialog != null){progressDialog.update(value: 100);}
  }

  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);
        _tasks.add(task);
      }
    });

    return _tasks;
  }

  bool selecting = false;
  Widget TaskCard(
      BuildContext context, String name, bool productive, Color color) {
    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,
                                    style: TextStyle(color: Colors.white)),
                                // Icon(Icons.analytics, color: color, size: 20,),
                                Icon(Icons.circle,
                                    color: (productive)
                                        ? Colors.green
                                        : Colors.red)
                              ]),
                        ],
                      )))),
          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{
    progressDialog.show(max: 100, msg: 'Deleteing ${selectedTasks.length} Task Types');
    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(() {
      progressDialog.update(value: 100);
    });

  }

}

List<String> selectedTasks = [];
