package com.kbs.kbsintranett;

import android.app.AlertDialog;
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.Navigation;
import androidx.navigation.fragment.NavHostFragment;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.gson.JsonElement;
import java.util.ArrayList;
import java.util.Collections;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CalendarDetailsBottomSheet extends BottomSheetDialogFragment {
    private CalendarEvent event;

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

    @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);
        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() + ")");

        if (!event.getDescription().isEmpty()) {
            // Skjul #varsel-taggen for visning
            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()) {
            adminLayout.setVisibility(View.VISIBLE);

            btnDelete.setOnClickListener(v -> confirmDelete());

            btnEdit.setOnClickListener(v -> {
                // Send eventet videre til redigering
                Bundle bundle = new Bundle();
                bundle.putSerializable("edit_event", event);
                // Vi må navigere via parent fragmentets navController
                NavHostFragment.findNavController(this).navigate(R.id.navigation_create_event, bundle);
                dismiss();
            });
        }

        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() {
        // Vi må sende en CreateEventRequest med ID for å slette
        // Vi trenger ikke fylle ut alt, bare ID og kalendertype
        // Siden vi ikke vet nøyaktig hvilken kalender den kom fra (APIet gir ikke det),
        // prøver vi "Felles" som default, eller prøver å slette fra ID.
        // PHP-koden vi lagde støtter sletting basert på ID hvis vi sender riktig kalendertype.
        // For nå antar vi "Felles" eller looper i backend. I V11.3 PHP scriptet sletter den basert på ID i valgt kalender.

        CreateEventRequest req = new CreateEventRequest(
                "", "", "", "", "", "Felles", 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();
                    dismiss();
                    // Her burde vi ideelt sett oppdatert listen bak, men brukeren kan dra for å oppdatere
                } else {
                    Toast.makeText(getContext(), "Kunne ikke slette (Er det en felles-hendelse?)", Toast.LENGTH_LONG).show();
                }
            }

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