package com.kbs.kbsintranett;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AddTaskBottomSheet extends BottomSheetDialogFragment {

    private EditText etTitle, etDesc;
    private Button btnDate, btnUsers, btnSave, btnClearDate; // NYTT
    private TextView txtSheetTitle, txtDatePreview, txtUsersPreview;

    private Calendar dueDate = Calendar.getInstance();
    private boolean hasDate = true; // NYTT

    private List<User> filteredUsers = new ArrayList<>();
    private List<User> selectedUsers = new ArrayList<>();
    private TaskItem taskToEdit = null;

    public interface OnTaskAddedListener {
        void onTaskAdded(TaskItem task);
        void onTaskUpdated(TaskItem task);
    }

    private OnTaskAddedListener listener;

    public void setOnTaskAddedListener(OnTaskAddedListener listener) {
        this.listener = listener;
    }

    public void setTaskToEdit(TaskItem task) {
        this.taskToEdit = task;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        BottomSheetDialog dialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState);
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        dialog.setOnShowListener(dialogInterface -> {
            BottomSheetDialog d = (BottomSheetDialog) dialogInterface;
            View bottomSheet = d.findViewById(com.google.android.material.R.id.design_bottom_sheet);
            if (bottomSheet != null) {
                BottomSheetBehavior.from(bottomSheet).setState(BottomSheetBehavior.STATE_EXPANDED);
            }
        });
        return dialog;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.bottom_sheet_add_task, container, false);

        txtSheetTitle = v.findViewById(R.id.txt_sheet_title);
        etTitle = v.findViewById(R.id.et_task_title);
        etDesc = v.findViewById(R.id.et_task_desc);
        btnDate = v.findViewById(R.id.btn_task_date);
        btnClearDate = v.findViewById(R.id.btn_clear_date); // NYTT
        btnUsers = v.findViewById(R.id.btn_task_users);
        btnSave = v.findViewById(R.id.btn_save_task);
        txtDatePreview = v.findViewById(R.id.txt_date_preview);
        txtUsersPreview = v.findViewById(R.id.txt_users_preview);

        if (taskToEdit != null) {
            txtSheetTitle.setText("Rediger Oppgave");
            etTitle.setText(taskToEdit.getTitle());
            etDesc.setText(taskToEdit.getDescription());

            if (taskToEdit.getDueDate() > 0) {
                dueDate.setTimeInMillis(taskToEdit.getDueDate());
                hasDate = true;
            } else {
                hasDate = false;
            }
            btnSave.setText("Oppdater Oppgave");
        } else {
            dueDate.add(Calendar.DAY_OF_MONTH, 1);
            hasDate = true;
        }

        updateDatePreview();

        btnDate.setOnClickListener(view -> {
            new DatePickerDialog(getContext(), (d, y, m, day) -> {
                dueDate.set(y, m, day);
                hasDate = true;
                updateDatePreview();
            }, dueDate.get(Calendar.YEAR), dueDate.get(Calendar.MONTH), dueDate.get(Calendar.DAY_OF_MONTH)).show();
        });

        // NYTT: Knapp for å fjerne frist
        btnClearDate.setOnClickListener(v1 -> {
            hasDate = false;
            updateDatePreview();
        });

        btnUsers.setOnClickListener(view -> showUserSelectionDialog());
        btnSave.setOnClickListener(view -> saveTask());

        fetchAndFilterUsers();

        return v;
    }

    private void fetchAndFilterUsers() {
        RetrofitClient.getApiService().getUsersList().enqueue(new Callback<List<User>>() {
            @Override
            public void onResponse(Call<List<User>> call, Response<List<User>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    filteredUsers = UserFilterHelper.getFilteredUsers(response.body());

                    if (taskToEdit != null) {
                        selectedUsers.clear();
                        Map<String, Boolean> currentAssignees = taskToEdit.getAssigneeStatus();
                        for (User u : filteredUsers) {
                            if (currentAssignees.containsKey(u.getEmail())) {
                                selectedUsers.add(u);
                            }
                        }
                        updateUsersPreview();
                    }
                }
            }
            @Override
            public void onFailure(Call<List<User>> call, Throwable t) {}
        });
    }

    private void showUserSelectionDialog() {
        if (filteredUsers.isEmpty()) {
            Toast.makeText(getContext(), "Henter tilgjengelige personer...", Toast.LENGTH_SHORT).show();
            return;
        }
        String[] names = new String[filteredUsers.size()];
        boolean[] checked = new boolean[filteredUsers.size()];
        for (int i = 0; i < filteredUsers.size(); i++) {
            names[i] = filteredUsers.get(i).getName();
            boolean isSelected = false;
            for(User su : selectedUsers) {
                if(su.getEmail().equalsIgnoreCase(filteredUsers.get(i).getEmail())) {
                    isSelected = true;
                    break;
                }
            }
            checked[i] = isSelected;
        }
        new AlertDialog.Builder(getContext())
                .setTitle("Tildel til...")
                .setMultiChoiceItems(names, checked, (dialog, which, isChecked) -> {
                    User user = filteredUsers.get(which);
                    if (isChecked) {
                        selectedUsers.add(user);
                    } else {
                        selectedUsers.removeIf(u -> u.getEmail().equalsIgnoreCase(user.getEmail()));
                    }
                })
                .setPositiveButton("OK", (dialog, which) -> updateUsersPreview())
                .show();
    }

    private void updateUsersPreview() {
        if (selectedUsers.isEmpty()) txtUsersPreview.setText("Kun meg");
        else if (selectedUsers.size() == 1) txtUsersPreview.setText(selectedUsers.get(0).getName());
        else txtUsersPreview.setText(selectedUsers.size() + " personer valgt");
    }

    private void updateDatePreview() {
        if (hasDate) {
            SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy", Locale.getDefault());
            txtDatePreview.setText("Frist: " + sdf.format(dueDate.getTime()));
            btnClearDate.setVisibility(View.VISIBLE);
        } else {
            txtDatePreview.setText("Ingen frist");
            btnClearDate.setVisibility(View.GONE);
        }
    }

    private void saveTask() {
        String title = etTitle.getText().toString().trim();
        if (title.isEmpty()) {
            etTitle.setError("Mangler tittel");
            return;
        }

        long finalDueDate = hasDate ? dueDate.getTimeInMillis() : 0;

        if (taskToEdit != null) {
            Map<String, Boolean> oldStatus = taskToEdit.getAssigneeStatus();
            taskToEdit.getAssigneeStatus().clear();

            if (selectedUsers.isEmpty()) {
                String myEmail = UserManager.getInstance().getUserEmail();
                taskToEdit.addAssignee(myEmail);
                if (oldStatus.containsKey(myEmail)) taskToEdit.setParticipantStatus(myEmail, oldStatus.get(myEmail));
            } else {
                for (User u : selectedUsers) {
                    taskToEdit.addAssignee(u.getEmail());
                    if (oldStatus.containsKey(u.getEmail())) {
                        taskToEdit.setParticipantStatus(u.getEmail(), oldStatus.get(u.getEmail()));
                    }
                }
            }
            taskToEdit.setTitle(title);
            taskToEdit.setDescription(etDesc.getText().toString());
            taskToEdit.setDueDate(finalDueDate);
            if (listener != null) listener.onTaskUpdated(taskToEdit);
        } else {
            TaskItem newTask = new TaskItem(title, etDesc.getText().toString(), finalDueDate);
            if (selectedUsers.isEmpty()) {
                newTask.addAssignee(UserManager.getInstance().getUserEmail());
            } else {
                for (User u : selectedUsers) newTask.addAssignee(u.getEmail());
            }
            if (listener != null) listener.onTaskAdded(newTask);
        }
        dismiss();
    }
}