import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:intl/intl.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';
import 'User.dart' as User;
import 'Data.dart';

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

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

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

class _NewCategoryState extends State<NewCategory> {
  TextEditingController nameController = TextEditingController();
  bool productive = true;
  Color pickerColor = Colors.blue;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('New Category')),
        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('Category Name')),
                                Container(
                                  padding: EdgeInsets.all(10),
                                  child: TextField(
                                    controller: nameController,
                                    decoration: InputDecoration(
                                        hintText:
                                            'ex: Study, Games, Relax, etc...',
                                        border: OutlineInputBorder()),
                                  ),
                                ),
                                Divider(),
                                Container(
                                    padding: EdgeInsets.all(10),
                                    child: Row(
                                        mainAxisSize: MainAxisSize.max,
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text('Productivity',
                                              style: TextStyle(fontSize: 18)),
                                          Switch(
                                            value: productive,
                                            onChanged: (value) {
                                              setState(() {
                                                productive = value;
                                              });
                                            },
                                          )
                                        ])),
                                Divider(),
                                Container(
                                    margin: EdgeInsets.all(10),
                                    child: InkWell(
                                        onTap: () => pickColor(context),
                                        child: Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          mainAxisSize: MainAxisSize.max,
                                          children: [
                                            Text("Category Color ",
                                                style: TextStyle(fontSize: 18)),
                                            Icon(Icons.circle,
                                                size: 40, color: pickerColor)
                                          ],
                                        )))
                              ]),
                            ],
                          ))),
                  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: () {
                                        add_action();
                                      },
                                      child: Text('Add Category',
                                          style: TextStyle(fontSize: 20))))),
                        ],
                      ))
                ])));
  }

  void pickColor(BuildContext context) => showDialog(
      context: context,
      builder: (context) => AlertDialog(
            title: Text('Pick Color for Category'),
            content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
              MaterialPicker(
                pickerColor: pickerColor,
                onColorChanged: (color){
                  setState(() {
                    pickerColor=color;
                  });
                },
                enableLabel: false,
                portraitOnly: true,
              ),
              TextButton(
                child: Text('Select', style: TextStyle(fontSize: 20)),
                onPressed: () => Navigator.of(context).pop(),
              )
            ]),
          ));

  void add_action() async{
    String catName = nameController.value.text;
    
    if(catName.length< 2){
      showAlertDialog(context, 'Category needs a name', 'Please enter a name for this category');
      return;
    }
    var hex = '#${pickerColor.value.toRadixString(16)}';
    await User.UserOperations.addCategory(catName, hex, productive);
    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;
    },
  );
}