package com.example.todojava;

import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.todojava.data.Todo;
import com.example.todojava.databinding.DialogTodoFormBinding;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;

public class TodoFormDialogFragment extends DialogFragment {

    private static final String ARG_TODO_ID = "todo_id";
    private static final String ARG_TODO_TITLE = "todo_title";
    private static final String ARG_TODO_CATEGORY = "todo_category";
    private static final String ARG_TODO_PRIORITY = "todo_priority";
    private static final String ARG_TODO_COMPLETED = "todo_completed";
    private static final String ARG_TODO_CREATED_AT = "todo_created_at";

    private DialogTodoFormBinding binding;
    private TodoViewModel viewModel;

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

    public static TodoFormDialogFragment newInstance(Todo todo) {
        TodoFormDialogFragment fragment = new TodoFormDialogFragment();
        Bundle args = new Bundle();
        args.putLong(ARG_TODO_ID, todo.getId());
        args.putString(ARG_TODO_TITLE, todo.getTitle());
        args.putString(ARG_TODO_CATEGORY, todo.getCategory());
        args.putString(ARG_TODO_PRIORITY, todo.getPriority());
        args.putBoolean(ARG_TODO_COMPLETED, todo.isCompleted());
        args.putLong(ARG_TODO_CREATED_AT, todo.getCreatedAt());
        fragment.setArguments(args);
        return fragment;
    }

    private boolean isEditing() {
        return getArguments() != null && getArguments().containsKey(ARG_TODO_ID);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        binding = DialogTodoFormBinding.inflate(LayoutInflater.from(getContext()));
        viewModel = new ViewModelProvider(requireActivity()).get(TodoViewModel.class);

        if (isEditing()) {
            prefillForm();
        }

        String title = isEditing() ? getString(R.string.edit_todo) : getString(R.string.add_todo);

        return new MaterialAlertDialogBuilder(requireContext())
                .setTitle(title)
                .setView(binding.getRoot())
                .setPositiveButton(R.string.save, (dialog, which) -> saveTodo())
                .setNegativeButton(R.string.cancel, null)
                .create();
    }

    private void prefillForm() {
        Bundle args = getArguments();
        if (args == null) return;

        binding.editTitle.setText(args.getString(ARG_TODO_TITLE, ""));

        String category = args.getString(ARG_TODO_CATEGORY, "Personal");
        switch (category) {
            case "Personal":
                binding.chipPersonal.setChecked(true);
                break;
            case "Work":
                binding.chipWork.setChecked(true);
                break;
            case "Shopping":
                binding.chipShopping.setChecked(true);
                break;
            case "Health":
                binding.chipHealth.setChecked(true);
                break;
            case "Learning":
                binding.chipLearning.setChecked(true);
                break;
        }

        String priority = args.getString(ARG_TODO_PRIORITY, "Medium");
        switch (priority) {
            case "Low":
                binding.chipLow.setChecked(true);
                break;
            case "Medium":
                binding.chipMedium.setChecked(true);
                break;
            case "High":
                binding.chipHigh.setChecked(true);
                break;
        }
    }

    private String getSelectedCategory() {
        int checkedId = binding.categoryChipGroup.getCheckedChipId();
        if (checkedId == R.id.chipPersonal) return "Personal";
        if (checkedId == R.id.chipWork) return "Work";
        if (checkedId == R.id.chipShopping) return "Shopping";
        if (checkedId == R.id.chipHealth) return "Health";
        if (checkedId == R.id.chipLearning) return "Learning";
        return "Personal";
    }

    private String getSelectedPriority() {
        int checkedId = binding.priorityChipGroup.getCheckedChipId();
        if (checkedId == R.id.chipLow) return "Low";
        if (checkedId == R.id.chipMedium) return "Medium";
        if (checkedId == R.id.chipHigh) return "High";
        return "Medium";
    }

    private void saveTodo() {
        String title = binding.editTitle.getText() != null
                ? binding.editTitle.getText().toString().trim() : "";

        if (title.isEmpty()) {
            return;
        }

        String category = getSelectedCategory();
        String priority = getSelectedPriority();

        if (isEditing()) {
            Bundle args = getArguments();
            Todo todo = new Todo(title, category, priority);
            todo.setId(args.getLong(ARG_TODO_ID));
            todo.setCompleted(args.getBoolean(ARG_TODO_COMPLETED, false));
            todo.setCreatedAt(args.getLong(ARG_TODO_CREATED_AT, System.currentTimeMillis()));
            viewModel.update(todo);
        } else {
            Todo todo = new Todo(title, category, priority);
            viewModel.insert(todo);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}
