import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:intl/intl.dart';
import 'package:tasktracker/NewCategory.dart';
import 'package:tasktracker/NewProject.dart';
import 'Data.dart';
import 'User.dart' as User;

DateFormat dateTimeFormat = DateFormat("yyyy-MM-dd HH:mm:ss");
DateFormat durationFormat = DateFormat("HH:mm:ss");

class NewTask extends StatefulWidget {
  NewTask({Key? key, this.t_cat, this.t_name, this.t_relProj}) : super(key: key);
  late String? t_name;
  late String? t_cat;
  late String? t_relProj;
  @override
  _NewTaskState createState() => _NewTaskState(t_cat: t_cat, t_name: t_name, t_relProj: t_relProj);
}

List<String> getCategoryNames(){
  List<String> _cats = [];
  _cats.add('+Add New Category');
  User.categories.forEach((element) {
    String name = element.name;
    _cats.add(name);
  });
  return _cats;
}

List<String> getProjectNames(){
  List<String> _projects = [];
  _projects.add("None");
  _projects.add('+Add New Project');
  User.projects.forEach((element) {
    String name = element.getName();
    _projects.add(name);
  });
  return _projects;
}

String selectedCat = User.categories[0].name;
String selectedProj = "None";
class _NewTaskState extends State<NewTask> {
  bool editing = false;
  String? oldName;
  _NewTaskState({String? t_name, String? t_cat, String? t_relProj}){
    if(t_name !=null && t_cat != null){
      editing = true;
      oldName = t_name;
    }

    nameController.text = t_name ?? '';
    selectedCat  = t_cat ?? User.categories[0].name;
    selectedProj = t_relProj ?? 'None';
  }

  TextEditingController nameController = TextEditingController();
  bool productive = true;

  @override
  Widget build(BuildContext context) {
    List<String> cats = getCategoryNames();
    return Scaffold(
        appBar: AppBar(title: Text('${(editing) ? 'Edit ' : 'New '} Task Type')),
        body: Container(
            height: MediaQuery.of(context).size.height,
            child: Column(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  SingleChildScrollView(
                      child: Padding(
                          padding: EdgeInsets.fromLTRB(20, 50, 20, 50),
                          child: Column(
                            children: [
                              Column(children: [
                                Container(
                                    padding: EdgeInsets.all(10),
                                    child: Text('Task Type Name')),
                                Container(
                                  padding: EdgeInsets.all(10),
                                  child: TextField(
                                    controller: nameController,
                                    decoration: InputDecoration(
                                      hintText: 'ex: Study Science, Play CS:GO, etc...',
                                      border: OutlineInputBorder()
                                    ),
                                  ),
                                ),
                                Divider(),
                                Container(
                                    padding: EdgeInsets.all(10),
                                    child: Text('Category')),
                                Container(
                                    padding: EdgeInsets.symmetric(
                                        horizontal: 12, vertical: 1),
                                    decoration: BoxDecoration(
                                        color: Colors.blueGrey,
                                        borderRadius: BorderRadius.circular(12),
                                        border: Border.all(
                                            color: Colors.grey, width: 2)),
                                    child: DropdownButton<String>(
                                        dropdownColor: Colors.blueGrey,
                                        iconSize: 30,
                                        elevation: 10,
                                        borderRadius: BorderRadius.circular(10),
                                        value: selectedCat,
                                        isExpanded: true,
                                        items: cats.map<DropdownMenuItem<String>>(
                                            (String value) {

                                          return DropdownMenuItem<String>(
                                            value: value,
                                            child: Text(value),
                                          );
                                        }).toList(),
                                        onChanged:(selectedProj == 'None') ? (String? _value) {
                                          if(_value != null) {
                                            if (_value.contains("+Add New Category")) {
                                              Navigator.of(context).push(MaterialPageRoute(builder: (context)=>NewCategory()));
                                            }else{
                                              selectedCat = _value!;
                                            }
                                          }
                                          setState(() {

                                          });
                                        } : null)),
                                Padding(
                                  padding: const EdgeInsets.fromLTRB(0, 20, 0, 10),
                                  child: Text('Related Project'),
                                ),
                                Container(
                                    padding: EdgeInsets.symmetric(
                                        horizontal: 12, vertical: 1),
                                    decoration: BoxDecoration(
                                        color: Colors.blueGrey,
                                        borderRadius: BorderRadius.circular(12),
                                        border: Border.all(
                                            color: Colors.grey, width: 2)),
                                    child: DropdownButton<String>(
                                        dropdownColor: Colors.blueGrey,
                                        iconSize: 30,
                                        elevation: 10,
                                        borderRadius: BorderRadius.circular(10),
                                        value: selectedProj,
                                        isExpanded: true,
                                        items: getProjectNames().map<DropdownMenuItem<String>>(
                                                (String value) {

                                              return DropdownMenuItem<String>(
                                                value: value,
                                                child: Text(value),
                                              );
                                            }).toList(),
                                        onChanged: (String? _value) async{
                                          if(_value != null) {
                                            if (_value.contains("+Add New Project")) {
                                              Navigator.of(context).push(MaterialPageRoute(builder: (context)=>NewProject()));
                                            }else{
                                              selectedProj = _value!;
                                              if(_value.contains("None")){

                                              }else{
                                                Project? relProj = await User.getProjectFromId(selectedProj);
                                                if(relProj==null){

                                                }else{
                                                  selectedCat = relProj.cat!.name;
                                                }
                                              }
                                            }
                                          }
                                          setState(() {

                                          });
                                        })),
                                Container(
                                    child: Divider(
                                  height: 30,
                                )),
                              ]),
                            ],
                          ))),
                  Container(
                      padding:
                          EdgeInsets.symmetric(vertical: 10, horizontal: 20),
                      child: Row(
                        mainAxisSize: MainAxisSize.max,
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          Expanded(
                              flex: 5,
                              child: Container(
                                padding: EdgeInsets.symmetric(horizontal: 10, vertical: 0),
                                  child: ElevatedButton(

                                    style:ElevatedButton.styleFrom(
                                        primary: Colors.red,
                                        shape: StadiumBorder()
                                    ),
                                      onPressed: () {
                                        setState(() {
                                          Navigator.pop(context);
                                        });
                                      },
                                      child: Text('Back',
                                          style: TextStyle(fontSize: 20))))),
                          Expanded(
                              flex: 6,
                            child: Container(
                                padding: EdgeInsets.symmetric(horizontal: 10, vertical: 0),
                                child: ElevatedButton(
                                  style:ElevatedButton.styleFrom(
                                      primary: Colors.green,
                                      shape: StadiumBorder()
                                  ),
                                  onPressed: () {
                                    setState(() {
                                      if(editing){
                                        edit_action();
                                      }else {
                                        add_action();
                                      }
                                    });
                                  },
                                  child: Text((editing) ? 'Apply' : 'Add Task Type',
                                      style: TextStyle(fontSize: 20))))),
                        ],
                      ))
                ])));
  }

  void add_action() async{
    String catName = nameController.value.text;
    print('adding Task Type : $catName, $selectedCat');
    if(catName.length< 2){
      showAlertDialog(context, 'Category needs a name', 'Please enter a name for this category');
      return;
    }
    await User.UserOperations.addTaskType(catName,selectedCat,relatedProject: (selectedProj == 'None') ? '' : selectedProj);
    Navigator.of(context).popUntil((route){
      return route.isFirst;
    });
  }

  void edit_action() async{
    String catName = nameController.value.text;
    print('editing Task Type $oldName => : $catName, $selectedCat');
    if(catName.length< 2){
      showAlertDialog(context, 'Category needs a name', 'Please enter a name for this category');
      return;
    }
    await User.UserOperations.editTaskType(oldName! ,catName,selectedCat,relatedProject: (selectedProj == 'None') ? '' : selectedProj);
    Navigator.of(context).popUntil((route){
      return route.isFirst;
    });
  }
}

String _printDuration(Duration duration) {
  String twoDigits(int n) => n.toString().padLeft(2, "0");
  String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
  String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
  return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
}
showAlertDialog(BuildContext context, String title, String message) {

  // set up the button
  Widget okButton = TextButton(
    child: Text("OK"),
    onPressed: () { Navigator.of(context).pop(); },
  );

  // set up the AlertDialog
  AlertDialog alert = AlertDialog(
    title: Text(title),
    content: Text(message),
    actions: [
      okButton,
    ],
  );

  // show the dialog
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );
}