package com.example.doitnow;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.doitnow.Model.ToDoModel;
import com.example.doitnow.Utils.DatabaseHandler;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.datepicker.MaterialDatePicker;
import com.google.android.material.timepicker.MaterialTimePicker;
import com.google.android.material.timepicker.TimeFormat;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class AddNewTask extends BottomSheetDialogFragment {

    public static final String TAG = "AddNewTask";

    private EditText newTaskText;
    private EditText startTimeEdit;
    private EditText endTimeEdit;
    private DatabaseHandler db;

    private Calendar startCalendar;
    private Calendar endCalendar;

    public static AddNewTask newInstance() {
        return new AddNewTask();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.new_task, container, false);
        newTaskText = view.findViewById(R.id.newTaskText);
        startTimeEdit = view.findViewById(R.id.startTimeEdit);
        endTimeEdit = view.findViewById(R.id.endTimeEdit);
        View saveButton = view.findViewById(R.id.newTaskButton);

        db = new DatabaseHandler(requireContext());
        db.openDatabase();

        startCalendar = Calendar.getInstance();
        endCalendar = Calendar.getInstance();

        startTimeEdit.setOnClickListener(v -> openDateTimePicker(startCalendar, startTimeEdit));
        endTimeEdit.setOnClickListener(v -> openDateTimePicker(endCalendar, endTimeEdit));

        saveButton.setOnClickListener(v -> {
            String taskText = newTaskText.getText().toString();
            if (!TextUtils.isEmpty(taskText)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
                String start = sdf.format(startCalendar.getTime());
                String end = sdf.format(endCalendar.getTime());

                Bundle args = getArguments();
                if (args != null && args.containsKey("id")) {
                    // 编辑任务
                    int id = args.getInt("id");
                    ToDoModel task = new ToDoModel();
                    task.setId(id);
                    task.setTask(taskText);
                    task.setStartTime(start);
                    task.setEndTime(end);
                    task.setStatus(0); // 可根据需要修改
                    db.updateTask(task);
                } else {
                    // 添加任务
                    ToDoModel task = new ToDoModel();
                    task.setTask(taskText);
                    task.setStartTime(start);
                    task.setEndTime(end);
                    task.setStatus(0);
                    db.insertTask(task);
                }

                // 回传结果，通知刷新
                Bundle result = new Bundle();
                result.putBoolean("taskAdded", true);
                getParentFragmentManager().setFragmentResult("taskAdded", result);

                dismiss();
            }
            else{
                newTaskText.setError("任務不可為空");
                return;
            }
        });

        Bundle args = getArguments();
        if (args != null) {
            String task = args.getString("task");
            String start = args.getString("startTime");
            String end = args.getString("endTime");

            newTaskText.setText(task);
            startTimeEdit.setText(start);
            endTimeEdit.setText(end);

            // 解析 startTime 字符串为 Calendar 类型
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
                Date startDate = sdf.parse(start);
                Date endDate = sdf.parse(end);

                if (startDate != null) startCalendar.setTime(startDate);
                if (endDate != null) endCalendar.setTime(endDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }


        return view;
    }

    private void openDateTimePicker(Calendar targetCalendar, EditText targetEditText) {
        MaterialDatePicker<Long> datePicker = MaterialDatePicker.Builder.datePicker()
                .setTitleText("選擇日期")
                .setSelection(MaterialDatePicker.todayInUtcMilliseconds())
                //.setTheme(R.style.CustomDatePickerTheme)
                .build();

        datePicker.addOnPositiveButtonClickListener(selection -> {
            targetCalendar.setTimeInMillis(selection);
            openTimePicker(targetCalendar, targetEditText);
        });

        datePicker.show(getParentFragmentManager(), "DATE_PICKER");
    }

    private void openTimePicker(Calendar calendar, EditText editText) {
        MaterialTimePicker timePicker = new MaterialTimePicker.Builder()
                .setTitleText("選擇時間")
                .setTimeFormat(TimeFormat.CLOCK_24H)
                .setHour(calendar.get(Calendar.HOUR_OF_DAY))
                .setMinute(calendar.get(Calendar.MINUTE))
                .build();

        timePicker.addOnPositiveButtonClickListener(v -> {
            calendar.set(Calendar.HOUR_OF_DAY, timePicker.getHour());
            calendar.set(Calendar.MINUTE, timePicker.getMinute());

            String formatted = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
                    .format(calendar.getTime());
            editText.setText(formatted);
        });

        timePicker.show(getParentFragmentManager(), "TIME_PICKER");
    }
}
