package com.kbs.kbsintranett;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.RadioGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;

import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;
import com.google.gson.JsonElement;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CreateEventFragment extends Fragment {
    private EditText etTitle, etDesc, etLocation;
    private Spinner spinnerCalendar, spinnerRecurrence;
    private ChipGroup chipGroupReminders;
    private Switch switchAllDay;
    private TextView txtPreview, txtSelectedParticipants;
    private Button btnStartDate, btnStartTime, btnEndDate, btnEndTime, btnSave, btnSelectParticipants;
    private RadioButton rbAll, rbSpecific;

    private Calendar startCal = Calendar.getInstance();
    private Calendar endCal = Calendar.getInstance();

    private String selectedRRule = null;
    private boolean isCustomRecurrence = false;

    private List<User> filteredUsers = new ArrayList<>();
    private String originalOrganizer = null;
    private CalendarEvent eventToEdit = null;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_create_event, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        etTitle = view.findViewById(R.id.et_title);
        etDesc = view.findViewById(R.id.et_desc);
        etLocation = view.findViewById(R.id.et_location);
        switchAllDay = view.findViewById(R.id.switch_all_day);
        spinnerCalendar = view.findViewById(R.id.spinner_calendar);
        spinnerRecurrence = view.findViewById(R.id.spinner_recurrence);
        chipGroupReminders = view.findViewById(R.id.chip_group_reminders);
        txtPreview = view.findViewById(R.id.txt_time_preview);
        txtSelectedParticipants = view.findViewById(R.id.txt_selected_participants);
        btnStartDate = view.findViewById(R.id.btn_start_date);
        btnStartTime = view.findViewById(R.id.btn_start_time);
        btnEndDate = view.findViewById(R.id.btn_end_date);
        btnEndTime = view.findViewById(R.id.btn_end_time);
        btnSave = view.findViewById(R.id.btn_save_event);
        btnSelectParticipants = view.findViewById(R.id.btn_select_participants);
        rbAll = view.findViewById(R.id.rb_visibility_all);
        rbSpecific = view.findViewById(R.id.rb_visibility_specific);

        startCal.add(Calendar.HOUR_OF_DAY, 1);
        startCal.set(Calendar.MINUTE, 0);
        endCal.setTime(startCal.getTime());
        endCal.add(Calendar.HOUR_OF_DAY, 1);

        setupCalendarSpinner();
        setupReminderChips();
        fetchUsers();

        // Trygg henting av Serializable for å unngå "unchecked" warning
        if (getArguments() != null && getArguments().containsKey("edit_event")) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                eventToEdit = getArguments().getSerializable("edit_event", CalendarEvent.class);
            } else {
                @SuppressWarnings("deprecation")
                CalendarEvent e = (CalendarEvent) getArguments().getSerializable("edit_event");
                eventToEdit = e;
            }

            if (eventToEdit != null) {
                prefillForm(eventToEdit);
                btnSave.setText("Oppdater Hendelse");
            }
        }

        updateRecurrenceSpinner();
        updateUI();

        switchAllDay.setOnCheckedChangeListener((btn, isChecked) -> updateUI());
        btnStartDate.setOnClickListener(v -> pickDate(startCal, true));
        btnEndDate.setOnClickListener(v -> pickDate(endCal, false));
        btnStartTime.setOnClickListener(v -> pickTime(startCal));
        btnEndTime.setOnClickListener(v -> pickTime(endCal));
        btnSave.setOnClickListener(v -> submitEvent());

        rbAll.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                btnSelectParticipants.setVisibility(View.GONE);
                txtSelectedParticipants.setVisibility(View.GONE);
            }
        });
        rbSpecific.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                btnSelectParticipants.setVisibility(View.VISIBLE);
                txtSelectedParticipants.setVisibility(View.VISIBLE);
            }
        });

        btnSelectParticipants.setOnClickListener(v -> showUserSelectionDialog());

        spinnerRecurrence.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (eventToEdit != null && position == 0 && selectedRRule != null) return;
                String selected = parent.getItemAtPosition(position).toString();
                if (selected.equals("Egendefinert...")) {
                    showCustomRecurrenceDialog();
                } else if (selected.startsWith("Ikke gjenta")) {
                    selectedRRule = null;
                } else {
                    generateStandardRRule(position);
                }
            }
            @Override public void onNothingSelected(AdapterView<?> parent) {}
        });
    }

    private void fetchUsers() {
        RetrofitClient.getApiService().getUsersList().enqueue(new Callback<List<User>>() {
            @Override
            public void onResponse(@NonNull Call<List<User>> call, @NonNull Response<List<User>> response) {
                if (!isAdded()) return;
                if (response.isSuccessful() && response.body() != null) {
                    filteredUsers = UserFilterHelper.getFilteredUsers(response.body());
                    if (eventToEdit != null) {
                        parseParticipantsFromDescription(eventToEdit.getDescription());
                    }
                }
            }
            @Override
            public void onFailure(@NonNull Call<List<User>> call, @NonNull Throwable t) {}
        });
    }

    private void showUserSelectionDialog() {
        if (filteredUsers.isEmpty()) {
            Toast.makeText(getContext(), "Ingen personer funnet.", Toast.LENGTH_SHORT).show();
            return;
        }

        String[] userNames = new String[filteredUsers.size()];
        boolean[] checkedItems = new boolean[filteredUsers.size()];

        for (int i = 0; i < filteredUsers.size(); i++) {
            userNames[i] = filteredUsers.get(i).getName();
            checkedItems[i] = filteredUsers.get(i).isSelected();
        }

        new AlertDialog.Builder(getContext())
                .setTitle("Velg deltakere")
                .setMultiChoiceItems(userNames, checkedItems, (dialog, which, isChecked) -> {
                    filteredUsers.get(which).setSelected(isChecked);
                })
                .setPositiveButton("OK", (dialog, which) -> updateParticipantPreview())
                .setNegativeButton("Avbryt", null)
                .show();
    }

    private void updateParticipantPreview() {
        StringBuilder sb = new StringBuilder("Valgte: ");
        int count = 0;
        for (User u : filteredUsers) {
            if (u.isSelected()) {
                if (count > 0) sb.append(", ");
                sb.append(u.getName());
                count++;
            }
        }
        if (count == 0) txtSelectedParticipants.setText("Ingen valgt");
        else txtSelectedParticipants.setText(sb.toString());
    }

    private void parseParticipantsFromDescription(String desc) {
        if (desc == null) return;
        Pattern p = Pattern.compile("#deltakere:([^\\s]+)");
        Matcher m = p.matcher(desc);

        if (m.find()) {
            rbSpecific.setChecked(true);
            String group = m.group(1);
            if (group != null) {
                String[] emails = group.split(",");
                for (String email : emails) {
                    for (User u : filteredUsers) {
                        if (u.getEmail().equalsIgnoreCase(email.trim())) {
                            u.setSelected(true);
                        }
                    }
                }
            }
            updateParticipantPreview();
        } else {
            rbAll.setChecked(true);
        }
    }

    private void prefillForm(CalendarEvent event) {
        etTitle.setText(event.getTitle());
        if (event.getDescription() != null) {
            Matcher m = Pattern.compile("#arrangor:(.+)").matcher(event.getDescription());
            if (m.find()) {
                String group = m.group(1);
                if (group != null) originalOrganizer = group.trim();
            }
        }

        String cleanDesc = event.getDescription()
                .replaceAll("#varsel:[\\d,]+", "")
                .replaceAll("#deltakere:[^\\s]+", "")
                .replaceAll("#arrangor:.+", "")
                .trim();
        etDesc.setText(cleanDesc);
        etLocation.setText(event.getLocation());

        if (spinnerCalendar.getAdapter() instanceof ArrayAdapter) {
            @SuppressWarnings("unchecked")
            ArrayAdapter<String> adapter = (ArrayAdapter<String>) spinnerCalendar.getAdapter();
            int position = adapter.getPosition(event.getCalendarName());
            if (position >= 0) spinnerCalendar.setSelection(position);
        }
        spinnerCalendar.setEnabled(false);

        try {
            SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
            SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            String start = event.getRawDate();
            if (start != null) {
                if (start.length() == 10) {
                    switchAllDay.setChecked(true);
                    startCal.setTime(simpleFormat.parse(start));
                    if (event.getRawEndDate() != null) {
                        Calendar c = Calendar.getInstance();
                        c.setTime(simpleFormat.parse(event.getRawEndDate()));
                        c.add(Calendar.DAY_OF_MONTH, -1);
                        endCal.setTime(c.getTime());
                    } else {
                        endCal.setTime(startCal.getTime());
                    }
                } else if (start.contains("T")) {
                    if (start.length() > 19) start = start.substring(0, 19);
                    startCal.setTime(isoFormat.parse(start));
                    String end = event.getRawEndDate();
                    if (end != null && end.contains("T")) {
                        if (end.length() > 19) end = end.substring(0, 19);
                        endCal.setTime(isoFormat.parse(end));
                    } else {
                        endCal.setTime(startCal.getTime());
                        endCal.add(Calendar.HOUR_OF_DAY, 1);
                    }
                }
            }
            List<Integer> existingReminders = event.getReminders();
            if (!existingReminders.isEmpty()) {
                for (int i = 0; i < chipGroupReminders.getChildCount(); i++) {
                    Chip chip = (Chip) chipGroupReminders.getChildAt(i);
                    Integer tag = (Integer) chip.getTag();
                    if (tag != null) {
                        chip.setChecked(existingReminders.contains(tag));
                    }
                }
            }
        } catch (Exception e) {
            Log.e("KBS_EDIT", "Feil ved prefill", e);
        }
    }

    private void setupCalendarSpinner() {
        List<String> calendars = UserManager.getInstance().getWriteableCalendars();
        if (calendars.isEmpty()) {
            calendars = new ArrayList<>();
            calendars.add("Felles");
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(requireContext(), android.R.layout.simple_spinner_item, calendars) {
            @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                TextView view = (TextView) super.getView(position, convertView, parent);
                view.setBackgroundColor(Color.parseColor(getCalendarColor(getItem(position))));
                view.setTextColor(Color.WHITE);
                view.setTypeface(null, Typeface.BOLD);
                return view;
            }
            @Override public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
                TextView view = (TextView) super.getDropDownView(position, convertView, parent);
                view.setTextColor(Color.parseColor(getCalendarColor(getItem(position))));
                view.setTypeface(null, Typeface.BOLD);
                return view;
            }
        };
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerCalendar.setAdapter(adapter);
    }

    private String getCalendarColor(String name) {
        if (name == null) return "#888888";
        switch (name) {
            case "Felles": return "#0069B3";
            case "AMU/HMS/Miljø": return "#2E7D32";
            case "Administrasjonen": return "#607D8B";
            case "Serviceavdelingen": return "#E65100";
            case "Automasjonsavdelingen": return "#2E7D32";
            case "Prosjektavdelingen": return "#7B1FA2";
            default: return "#888888";
        }
    }

    private void setupReminderChips() {
        chipGroupReminders.removeAllViews();
        addReminderChip("Ved start", 0);
        addReminderChip("5 min", 5);
        addReminderChip("10 min", 10);
        addReminderChip("15 min", 15);
        addReminderChip("30 min", 30);
        addReminderChip("1 t", 60);
        addReminderChip("2 t", 120);
        addReminderChip("1 d", 1440);
        addReminderChip("2 d", 2880);
        addReminderChip("1 u", 10080);

        if (eventToEdit == null) {
            for (int i=0; i<chipGroupReminders.getChildCount(); i++) {
                Chip c = (Chip) chipGroupReminders.getChildAt(i);
                Integer tag = (Integer) c.getTag();
                if (tag != null && tag == 15) c.setChecked(true);
            }
        }
    }

    private void addReminderChip(String text, int minutes) {
        Chip chip = new Chip(requireContext());
        chip.setText(text);
        chip.setTag(minutes);
        chip.setCheckable(true);
        chipGroupReminders.addView(chip);
    }

    private void updateRecurrenceSpinner() {
        String dayName = new SimpleDateFormat("EEEE", new Locale("no")).format(startCal.getTime());
        int dayOfMonth = startCal.get(Calendar.DAY_OF_MONTH);
        String monthName = new SimpleDateFormat("MMMM", new Locale("no")).format(startCal.getTime());
        int weekNo = (startCal.get(Calendar.DAY_OF_MONTH) - 1) / 7 + 1;
        List<String> options = new ArrayList<>();
        options.add("Ikke gjenta"); options.add("Daglig"); options.add("Ukentlig på " + dayName);
        options.add("Månedlig den " + dayOfMonth + "."); options.add("Månedlig den " + weekNo + ". " + dayName + "en");
        options.add("Årlig den " + dayOfMonth + ". " + monthName); options.add("Hver ukedag (man-fre)"); options.add("Egendefinert...");
        spinnerRecurrence.setAdapter(new ArrayAdapter<>(requireContext(), android.R.layout.simple_spinner_dropdown_item, options));
    }

    private void generateStandardRRule(int position) {
        switch (position) {
            case 1: selectedRRule = "RRULE:FREQ=DAILY"; break;
            case 2: selectedRRule = "RRULE:FREQ=WEEKLY"; break;
            case 3: selectedRRule = "RRULE:FREQ=MONTHLY"; break;
            case 4: selectedRRule = "RRULE:FREQ=MONTHLY;BYDAY=" + ((startCal.get(Calendar.DAY_OF_MONTH)-1)/7+1) + getDayCode(startCal.get(Calendar.DAY_OF_WEEK)); break;
            case 5: selectedRRule = "RRULE:FREQ=YEARLY"; break;
            case 6: selectedRRule = "RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR"; break;
            default: selectedRRule = null;
        }
    }

    private String getDayCode(int calendarDay) {
        switch (calendarDay) {
            case Calendar.MONDAY: return "MO"; case Calendar.TUESDAY: return "TU"; case Calendar.WEDNESDAY: return "WE";
            case Calendar.THURSDAY: return "TH"; case Calendar.FRIDAY: return "FR"; case Calendar.SATURDAY: return "SA";
            case Calendar.SUNDAY: return "SU"; default: return "MO";
        }
    }

    private void showCustomRecurrenceDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_custom_recurrence, null);
        EditText etInterval = view.findViewById(R.id.et_interval), etCount = view.findViewById(R.id.et_count);
        Spinner spinnerFreq = view.findViewById(R.id.spinner_freq);
        View layoutWeekdays = view.findViewById(R.id.layout_weekdays);
        ToggleButton[] toggles = {view.findViewById(R.id.tg_mon), view.findViewById(R.id.tg_tue), view.findViewById(R.id.tg_wed), view.findViewById(R.id.tg_thu), view.findViewById(R.id.tg_fri), view.findViewById(R.id.tg_sat), view.findViewById(R.id.tg_sun)};
        String[] labels = {"M", "T", "O", "T", "F", "L", "S"};
        for(int i=0; i<7; i++) { toggles[i].setText(labels[i]); toggles[i].setTextOn(labels[i]); toggles[i].setTextOff(labels[i]); }
        RadioGroup rgEnd = view.findViewById(R.id.rg_end); Button btnEndDatePicker = view.findViewById(R.id.btn_end_date_picker);
        Calendar customEndCal = Calendar.getInstance(); customEndCal.add(Calendar.MONTH, 1);
        btnEndDatePicker.setText(new SimpleDateFormat("d. MMM yyyy", Locale.getDefault()).format(customEndCal.getTime()));
        btnEndDatePicker.setOnClickListener(v -> {
            rgEnd.check(R.id.rb_date);
            new DatePickerDialog(requireContext(), (p, y, m, d) -> { customEndCal.set(y, m, d); btnEndDatePicker.setText(new SimpleDateFormat("d. MMM yyyy", Locale.getDefault()).format(customEndCal.getTime())); }, customEndCal.get(Calendar.YEAR), customEndCal.get(Calendar.MONTH), customEndCal.get(Calendar.DAY_OF_MONTH)).show();
        });
        spinnerFreq.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override public void onItemSelected(AdapterView<?> p, View v, int pos, long id) { layoutWeekdays.setVisibility(pos == 1 ? View.VISIBLE : View.GONE); }
            @Override public void onNothingSelected(AdapterView<?> p) {}
        });
        builder.setView(view); AlertDialog dialog = builder.create();
        view.findViewById(R.id.btn_cancel).setOnClickListener(v -> { dialog.dismiss(); spinnerRecurrence.setSelection(0); });
        view.findViewById(R.id.btn_done).setOnClickListener(v -> {
            StringBuilder rrule = new StringBuilder("RRULE:FREQ=");
            rrule.append(new String[]{"DAILY", "WEEKLY", "MONTHLY", "YEARLY"}[spinnerFreq.getSelectedItemPosition()]);
            if (!etInterval.getText().toString().isEmpty() && !etInterval.getText().toString().equals("1")) rrule.append(";INTERVAL=").append(etInterval.getText().toString());
            if (spinnerFreq.getSelectedItemPosition() == 1) {
                List<String> days = new ArrayList<>(); String[] codes = {"MO", "TU", "WE", "TH", "FR", "SA", "SU"};
                for (int i=0; i<7; i++) if (toggles[i].isChecked()) days.add(codes[i]);
                if (!days.isEmpty()) rrule.append(";BYDAY=").append(String.join(",", days));
            }
            if (rgEnd.getCheckedRadioButtonId() == R.id.rb_date) {
                customEndCal.set(Calendar.HOUR_OF_DAY, 23); customEndCal.set(Calendar.MINUTE, 59);
                SimpleDateFormat utc = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.US); utc.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
                rrule.append(";UNTIL=").append(utc.format(customEndCal.getTime()));
            } else if (rgEnd.getCheckedRadioButtonId() == R.id.rb_count) rrule.append(";COUNT=").append(etCount.getText().toString());
            selectedRRule = rrule.toString(); isCustomRecurrence = true; dialog.dismiss();
        });
        dialog.show();
    }

    private void pickDate(Calendar cal, boolean isStart) {
        new DatePickerDialog(requireContext(), (view, y, m, d) -> {
            cal.set(y, m, d);
            if (isStart) {
                if (endCal.before(startCal)) { endCal.setTime(startCal.getTime()); if (!switchAllDay.isChecked()) endCal.add(Calendar.HOUR_OF_DAY, 1); }
                updateRecurrenceSpinner(); if (!isCustomRecurrence) spinnerRecurrence.setSelection(0);
            }
            updateUI();
        }, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)).show();
    }

    private void pickTime(Calendar cal) {
        new TimePickerDialog(requireContext(), (view, h, m) -> {
            cal.set(Calendar.HOUR_OF_DAY, h); cal.set(Calendar.MINUTE, m);
            if (cal == startCal && endCal.before(startCal)) { endCal.setTime(startCal.getTime()); endCal.add(Calendar.HOUR_OF_DAY, 1); }
            updateUI();
        }, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), true).show();
    }

    private void updateUI() {
        boolean isAllDay = switchAllDay.isChecked();
        btnStartTime.setVisibility(isAllDay ? View.GONE : View.VISIBLE);
        btnEndTime.setVisibility(isAllDay ? View.GONE : View.VISIBLE);
        SimpleDateFormat dFmt = new SimpleDateFormat("dd.MM.yyyy", Locale.getDefault()), tFmt = new SimpleDateFormat("HH:mm", Locale.getDefault());
        btnStartDate.setText(dFmt.format(startCal.getTime())); btnEndDate.setText(dFmt.format(endCal.getTime()));
        btnStartTime.setText(tFmt.format(startCal.getTime())); btnEndTime.setText(tFmt.format(endCal.getTime()));
        String p = dFmt.format(startCal.getTime()) + (isAllDay ? "" : " " + tFmt.format(startCal.getTime())) + " - ";
        if (startCal.get(Calendar.YEAR) == endCal.get(Calendar.YEAR) && startCal.get(Calendar.DAY_OF_YEAR) == endCal.get(Calendar.DAY_OF_YEAR)) {
            p += (isAllDay ? "(Samme dag)" : tFmt.format(endCal.getTime()));
        } else p += dFmt.format(endCal.getTime()) + (isAllDay ? "" : " " + tFmt.format(endCal.getTime()));
        txtPreview.setText(p);
    }

    private void submitEvent() {
        String title = etTitle.getText().toString().trim();
        if (title.isEmpty()) { etTitle.setError("Mangler tittel"); return; }
        SimpleDateFormat sdf = new SimpleDateFormat(switchAllDay.isChecked() ? "yyyy-MM-dd" : "yyyy-MM-dd'T'HH:mm", Locale.getDefault());
        List<Integer> reminders = new ArrayList<>();
        for (int i=0; i<chipGroupReminders.getChildCount(); i++) {
            Chip c = (Chip) chipGroupReminders.getChildAt(i);
            Integer tag = (Integer) c.getTag();
            if (c.isChecked() && tag != null) reminders.add(tag);
        }
        String desc = etDesc.getText().toString();
        if (rbSpecific.isChecked()) {
            StringBuilder sb = new StringBuilder(); boolean first = true;
            for (User u : filteredUsers) if (u.isSelected()) { if (!first) sb.append(","); sb.append(u.getEmail()); first = false; }
            if (sb.length() > 0) desc += "\n\n#deltakere:" + sb.toString();
        }
        desc += "\n#arrangor:" + (originalOrganizer != null ? originalOrganizer : UserManager.getInstance().getUserDisplayName());

        String calSlug = spinnerCalendar.getSelectedItem() != null ? spinnerCalendar.getSelectedItem().toString() : "Felles";

        CreateEventRequest req = new CreateEventRequest(title, desc, etLocation.getText().toString(), sdf.format(startCal.getTime()), sdf.format(endCal.getTime()), calSlug, reminders, switchAllDay.isChecked(), selectedRRule);
        if (eventToEdit != null) req.id = eventToEdit.getId();

        Call<JsonElement> call = (eventToEdit != null) ? RetrofitClient.getApiService().updateCalendarEvent(req) : RetrofitClient.getApiService().createCalendarEvent(req);
        call.enqueue(new Callback<JsonElement>() {
            @Override public void onResponse(@NonNull Call<JsonElement> call, @NonNull Response<JsonElement> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(getContext(), "Lagret!", Toast.LENGTH_LONG).show();
                    Navigation.findNavController(requireView()).navigateUp();
                }
            }
            @Override public void onFailure(@NonNull Call<JsonElement> call, @NonNull Throwable t) { Toast.makeText(getContext(), "Feil!", Toast.LENGTH_SHORT).show(); }
        });
    }
}