import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tasktracker/Data.dart';
import 'package:tasktracker/NewProject.dart';
import 'package:tasktracker/NotificationsManager.dart';
import 'main.dart';
import 'User.dart' as User;

class Dialogs{
  static String syncingMessage = "Syncing";

  static 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(
      backgroundColor: Color(0xFF1F1F1F),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
      title: Text(title),
      content: Text(message),
      actions: [
        okButton,
      ],

    );

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

  static bool showing = false;
  static BuildContext? context;
  static List<Widget> popupsOpened=[];
  static waiting( String title){
    showing=true;
    context=navigatorKey.currentContext;
    if(context!=null) {
      return showDialog(
          context: context!,
          barrierDismissible: false,
          routeSettings: const RouteSettings(name: "Progress"),
          builder: (BuildContext context) {
            return AlertDialog(
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
              backgroundColor: Color(0xaa101010),
              title: Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  SpinKitChasingDots(color: Colors.green),
                  Expanded(child: Text(syncingMessage,textAlign: TextAlign.center,)),
                ],
              ),
            );
          }
      );
    }
  }

  static showQuestionDialog(String title, String message, {bool hasCancel = false, required Function(bool) onResponse}) async{
    context=navigatorKey.currentContext;

    if(context!=null) {
      return showDialog(
          context: context!,
          builder: (BuildContext context) {
            return AlertDialog(
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
              backgroundColor: Color(0xFF1C1C1C),
              title: Text(title),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(message)
                ],
              ),
              actions: [
                if(hasCancel)MaterialButton(
                  onPressed: (){
                    Navigator.of(context).pop();
                  },
                  child: Text('Cancel', style:TextStyle(color: Colors.grey)),
                ),
                MaterialButton(
                  onPressed: (){
                    onResponse(false);
                    Navigator.of(context).pop();
                },
                  child: Text('No', style:TextStyle(color: Colors.red)),
                ),
                MaterialButton(
                  onPressed: (){
                    onResponse(true);
                    Navigator.of(context).pop();
                  },
                  child: Text('Yes', style:TextStyle(color: Colors.green)),
                )
              ],
            );
          }
      );
    }else{
      print('context is null');
    }
  }

  static ongoing() async{
    List<String>? data= await User.getOngoingData();
    if(data == null){return;}
    
    context=navigatorKey.currentContext;
    if(context!=null) {
      return showDialog(
          context: context!,
          routeSettings: const RouteSettings(name: "Ongoing"),
          builder: (BuildContext context) {
            return AlertDialog(
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
              backgroundColor: Color(0xFF101010),
              title: Text('Take Action for Ongoing Activity'),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(''),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('Task : ${data[0]}'),
                      Text('Description: ${data[1]}'),
                      Text('Started Time: ${DateFormat("MM-dd hh:mm").format(DateTime.parse(data[2]))}')
                    ],
                  ),

                ],
              ),
              actions: [

                MaterialButton(onPressed: (){Navigator.of(context).pop();}, child: Text('Cancel', style:TextStyle(color: Colors.grey))),
                MaterialButton(onPressed: (){
                  User.CancelOngoingActivity();
                  NotificationManager.RescheduleNotifications();
                  Navigator.of(context).pop();
                }, child:Text('Remove', style:TextStyle(color: Colors.redAccent))),
                MaterialButton(
                  onPressed: (){
                    User.StopActivityTimer();
                    NotificationManager.RescheduleNotifications();
                    Navigator.of(context).pop();

                  },
                  child: Text('Complete', style:TextStyle(color: Colors.green)),
                ),

              ],
            );
          }
      );
    }
  }

  static showProjectDetails(Project project) async{
    context=navigatorKey.currentContext;
    List<Widget> stepWidgets = [];
    for (ProjectStep value in project.steps) {
      stepWidgets.add(Text('[${value.progress}%] ${value.eta}h ->    ${value.stepName}',style: TextStyle(fontSize: 14)));
    }
    if(context!=null) {
      return showDialog(
          context: context!,
          builder: (BuildContext context) {
            return AlertDialog(
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
              backgroundColor: Color(0xFF1C1C1C),
              title: Text(project.name),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("Deadline : ${DateFormat("yyyy-MM-dd").format(project.deadline)}"),
                  Divider(),
                  Text("Steps",style: TextStyle(fontWeight: FontWeight.bold)),
                  SizedBox(height: 20),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: stepWidgets,
                  ),
                  SizedBox(height: 30,),
                  Text("Estimate Time : ${project.eta}")
                ],
              ),
              actions: [
                MaterialButton(
                  onPressed: (){
                    User.UserOperations.deleteProject(project.name);
                    Navigator.of(context).pop();
                  },
                  child: Text('Delete', style:TextStyle(color: Colors.red)),
                ),
                MaterialButton(
                  onPressed: (){
                    Navigator.of(context).pop();
                    Navigator.of(context).push(MaterialPageRoute(builder: (context)=>NewProject(multiline: project.steps.isNotEmpty, projectName: project.name, selectedCategory: project.cat!.name,m_steps: project.steps,)));
                  },
                  child: Text('Edit', style:TextStyle(color: Colors.yellow)),
                ),
                MaterialButton(
                  onPressed: (){
                    Navigator.of(context).pop();
                  },
                  child: Text('Close', style:TextStyle(color: Colors.white)),
                )
              ],
            );
          }
      );
    }else{
      print('context is null');
    }
  }

  static completeStepDialog(Project project,Function(DateTime) onComplete, ProjectStep step) async{
    context=navigatorKey.currentContext;
    DateTime finishedDate = DateTime.now();
    DateFormat dateFormat = DateFormat('yyyy-MM-dd');
    if(context!=null) {
     // return StatefulBuilder(builder: (context, setState) {
      return showDialog(
          context: context!,
          builder: (BuildContext context) {
            return StatefulBuilder(builder: (context, setState)
            {
              return AlertDialog(
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
                backgroundColor: Color(0xFF1C1C1C),
                title: Text('Completed ${step.stepName}?'),
                content: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('When did you complete?'),
                    SizedBox(height: 20,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        InkWell(
                          onTap: () {
                            DatePicker.showDatePicker(context,
                                showTitleActions: true,
                                theme: DatePickerTheme(), onChanged: (date) {
                                  // print('change $date');
                                }, onConfirm: (date) {
                                  setState(() {
                                    finishedDate = date;
                                  });
                                }, currentTime: finishedDate, locale: LocaleType.en);
                            setState(() {});
                          },
                          child: Container(
                            decoration: BoxDecoration(
                                color: Colors.black26,
                                borderRadius: BorderRadius.circular(15)
                            ),
                            padding: EdgeInsets.symmetric(horizontal: 25, vertical: 10),
                            child:  Text((dateFormat.format(finishedDate) ==dateFormat.format(DateTime.now())) ? 'Today' : dateFormat.format(finishedDate), style: TextStyle(color: Colors.blue),),
                          ),
                        ),
                      ],
                    )
                  ],
                ),
                actions: [
                  MaterialButton(
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: Text('No', style: TextStyle(color: Colors.red)),
                  ),
                  MaterialButton(
                    color: Colors.green,
                    onPressed: () {
                      User.UserOperations.CompleteProjectStep(project, step, finishedDate);
                      Navigator.of(context).pop();
                    },
                    child: Text('Complete', style: TextStyle(color: Colors.white)),
                  ),
                ],
              );
            });
          }
      );
    }else{
      print('context is null');
    }
  }

  static showJournalLink(DateTime date) async{
    context=navigatorKey.currentContext;

    if(context!=null) {
      int journalId = -1;
      for (int i =0; i < User.journal.length; i++) {
        print('${User.journal[i].day } : $date');
        if(DateFormat('yyyy-MM-dd').format(User.journal[i].day) == DateFormat('yyyy-MM-dd').format(date)){
          journalId = i;
          break;
        }
      }
      if(journalId < 0){return;}
      String title= (User.journal[journalId].title!= null && User.journal[journalId].title!.isNotEmpty) ? (User.journal[journalId].title! + ' (${(DateFormat('MMMM-dd').format(date))})') : DateFormat('MMMM-dd').format(date);
      String description = User.journal[journalId].description ?? '';
      if(description.length > 60){
        description = description.substring(0,60) + '...(click more for more)';
      }
      return showDialog(
          context: context!,
          builder: (BuildContext context) {
            return AlertDialog(
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
              backgroundColor: Color(0xFF1C1C1C),
              title: Text(title),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(description)
                ],
              ),
              actions: [
                MaterialButton(
                  onPressed: (){
                    Navigator.of(context).pop();
                  },
                  child: Text('Back', style:TextStyle(color: Colors.red)),
                ),
                MaterialButton(
                  onPressed: (){
                    Navigator.of(context).pop();
                  },
                  child: Text('More', style:TextStyle(color: Colors.green)),
                )
              ],
            );
          }
      );
    }else{
      print('context is null');
    }
  }

  static hide(){
    showing=false;
    Navigator.of(navigatorKey.currentContext!).popUntil((route){
      return route.settings.name!="Progress";
    });
  }
}