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

class NewJournal extends StatefulWidget {
  NewJournal({Key? key, this.title, this.text, this.date}) : super(key: key);
  late String? title;
  late String? text;
  late DateTime? date;

  @override
  _NewJournalState createState() => _NewJournalState(title: title, text: text, m_date: date);
}

class _NewJournalState extends State<NewJournal> {
  bool editing =false;

  DateTime date=  DateTime.now();
  DateFormat dFormat =  DateFormat('yyyy-MM-dd');
  _NewJournalState({String? title, String? text, DateTime? m_date}){
    if(m_date!= null){
      editing = true;
      date=m_date;
      oldDate =m_date;
    }else{
      bool foundEmptyDate = false;
      while(!foundEmptyDate) {
        bool exist = false;
        for (var element in User.journal) {
          if (dFormat.format(element.day) == dFormat.format(date)) {
            //Wat!
            exist = true;
            break;
          }
        }
        if (!exist) {
          foundEmptyDate=true;
        }else{
          date = date.subtract(Duration(days: 1));
        }
      }
    }

    titleController.text = title??'';
    descriptionEditingController.text = text??'';
  }

  TextEditingController titleController = TextEditingController();
  TextEditingController descriptionEditingController = TextEditingController();
  bool productive = true;
  Color pickerColor = Colors.blue;
  DateTime oldDate = DateTime.now();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('${(editing) ? 'Edit' : 'New'} Journal Entry')),
        body: Container(
            height: MediaQuery.of(context).size.height,
            child: Column(mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
              Expanded(flex: 9,
                child: SingleChildScrollView(
                    child: Padding(
                        padding: EdgeInsets.fromLTRB(20, 50, 20, 50),
                        child: Column(
                          children: [
                            InkWell(
                              onTap: (){
                                DatePicker.showDatePicker(context,
                                    showTitleActions: true,
                                    minTime: User.activities[User.activities.length-1].startTime,
                                    maxTime: User.activities[0].startTime,
                                    theme: DatePickerTheme(), onChanged: (date) {
                                      // print('change $date');
                                    }, onConfirm: (newDate){
                                      bool exist =false;
                                      for (var element in User.journal) {
                                        if(dFormat.format(element.day) == dFormat.format(newDate)){
                                          //Wat!
                                          exist=true;
                                          break;
                                        }
                                      }

                                      if(exist){
                                        Dialogs.showAlertDialog(context, 'Cant duplicate entries!', 'Journal entry was found on this date, Please edit that instead of adding new entry.');
                                      }else {
                                        date = newDate;
                                      }

                                      setState(() {

                                      });
                                    }, currentTime: date, locale: LocaleType.en);
                              },
                              child: Container(
                                margin: EdgeInsets.symmetric(vertical: 10),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    FaIcon(FontAwesomeIcons.calendarDay),
                                    SizedBox(width: 10,),
                                    Text('Date : '),
                                    SizedBox(width: 30,),
                                    Text(
                                      dFormat.format(date),
                                      style: TextStyle(fontSize: 18),
                                    ),
                                    SizedBox(width: 30,),
                                  ],
                                ),
                              ),
                            ),
                            SizedBox(height: 10,),
                            Column(children: [
                              Container(
                                padding: EdgeInsets.all(10),
                                child: TextField(
                                  controller: titleController,
                                  decoration: InputDecoration(hintText: 'Title (something special happened this day)', border: OutlineInputBorder()),
                                ),
                              ),
                              Divider(),
                              Container(
                                padding: EdgeInsets.all(10),
                                child: TextField(

                                  maxLines: 25,
                                  minLines: 10,
                                  controller: descriptionEditingController,
                                  decoration: InputDecoration(hintText: 'So how was your day? Write it all down here!', border: OutlineInputBorder()),
                                ),
                              ),
                            ]),
                          ],
                        ))),
              ),
              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('${editing ? 'Edit ' : 'Add '}Entry', style: TextStyle(fontSize: 20))))),
                    ],
                  ))
            ])));
  }

  void add_action() async {
    String title = titleController.value.text;
    String text = descriptionEditingController.text;

    if (title.isEmpty && text.isEmpty) {
      showAlertDialog(context, 'Empty data', 'Journal entry is empty, Cannot add empty entries');
      return;
    }
    if(editing){
      await User.UserOperations.editJournal(oldDate,date,title,text);
    }else{
      bool exist =false;
      for (var element in User.journal) {
        if(element.day== date){
          //Wat!
          exist=true;
          break;
        }
      }

      if(exist){
        Dialogs.showAlertDialog(context, 'Cant duplicate entries!', 'Journal entry was found on this date, Please edit that instead of adding new entry.');
        return;
      }
      await User.UserOperations.addJournal(date, title, text);
    }
    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;
    },
  );
}
