package com.kbs.kbsintranett;

import android.app.AlertDialog;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.navigation.fragment.NavHostFragment;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.gson.JsonElement;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CalendarDetailsBottomSheet extends BottomSheetDialogFragment {
    private CalendarEvent event;
    private OnEventChangeListener changeListener;

    // Interface for å varsle foreldre-fragmentet om endringer
    public interface OnEventChangeListener {
        void onEventChanged();
    }

    public CalendarDetailsBottomSheet(CalendarEvent event) {
        this.event = event;
    }

    public void setOnEventChangeListener(OnEventChangeListener listener) {
        this.changeListener = listener;
    }

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

        TextView title = view.findViewById(R.id.sheet_title);
        TextView time = view.findViewById(R.id.sheet_time);
        TextView desc = view.findViewById(R.id.sheet_desc);
        TextView loc = view.findViewById(R.id.sheet_location);
        TextView calName = view.findViewById(R.id.sheet_calendar_name);

        LinearLayout adminLayout = view.findViewById(R.id.layout_admin_buttons);
        Button btnDelete = view.findViewById(R.id.btn_delete);
        Button btnEdit = view.findViewById(R.id.btn_edit);

        title.setText(event.getTitle());
        time.setText(event.getTime() + " (" + event.getDay() + ". " + event.getMonth() + ")");

        calName.setText(event.getCalendarName().toUpperCase());
        try {
            int color = Color.parseColor(event.getCalendarColor());
            calName.setBackgroundTintList(ColorStateList.valueOf(color));
        } catch (Exception e) {}

        if (!event.getDescription().isEmpty()) {
            String cleanDesc = event.getDescription().replaceAll("#varsel:[\\d,]+", "").trim();
            desc.setText(Html.fromHtml(cleanDesc, Html.FROM_HTML_MODE_COMPACT));
            desc.setVisibility(View.VISIBLE);
            desc.setMovementMethod(LinkMovementMethod.getInstance());
        } else {
            desc.setVisibility(View.GONE);
        }

        if (!event.getLocation().isEmpty()) {
            loc.setText("Sted: " + event.getLocation());
            loc.setVisibility(View.VISIBLE);
        } else {
            loc.setVisibility(View.GONE);
        }

        // Sjekk admin-rettigheter
        if (UserManager.getInstance().isEditorOrAbove()) {
            boolean canEdit = UserManager.getInstance().getWriteableCalendars().contains(event.getCalendarName())
                    || UserManager.getInstance().isAdmin();

            if (canEdit) {
                adminLayout.setVisibility(View.VISIBLE);
                btnDelete.setOnClickListener(v -> confirmDelete());
                btnEdit.setOnClickListener(v -> {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("edit_event", event);
                    NavHostFragment.findNavController(this).navigate(R.id.navigation_create_event, bundle);
                    dismiss();
                });
            } else {
                adminLayout.setVisibility(View.GONE);
            }
        }

        return view;
    }

    private void confirmDelete() {
        new AlertDialog.Builder(getContext())
                .setTitle("Slett hendelse")
                .setMessage("Er du sikker på at du vil slette '" + event.getTitle() + "'?")
                .setPositiveButton("Slett", (dialog, which) -> deleteEvent())
                .setNegativeButton("Avbryt", null)
                .show();
    }

    private void deleteEvent() {
        CreateEventRequest req = new CreateEventRequest(
                "", "", "", "", "", event.getCalendarName(), new ArrayList<>(), false, ""
        );
        req.id = event.getId();

        RetrofitClient.getApiService().deleteCalendarEvent(req).enqueue(new Callback<JsonElement>() {
            @Override
            public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(getContext(), "Slettet!", Toast.LENGTH_SHORT).show();

                    // VARSLE LISTEN OM AT NOE ER SLETTET
                    if (changeListener != null) {
                        changeListener.onEventChanged();
                    }

                    dismiss();
                } else {
                    Toast.makeText(getContext(), "Kunne ikke slette", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<JsonElement> call, Throwable t) {
                Toast.makeText(getContext(), "Nettverksfeil", Toast.LENGTH_SHORT).show();
            }
        });
    }
}