package com.kbs.kbsintranett;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
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 java.util.regex.Matcher;
import java.util.regex.Pattern;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

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

    private static final String PRIVATE_EVENT_COLOR = "#673AB7";

    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);
        TextView participantsView = view.findViewById(R.id.sheet_participants);
        TextView organizerView = view.findViewById(R.id.sheet_organizer); // NYTT

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

        // Sjekk om privat
        boolean isPrivate = event.getDescription() != null && event.getDescription().contains("#deltakere:");

        if (isPrivate) {
            calName.setText(event.getCalendarName().toUpperCase() + " (BEGRENSET INNSYN)");
            try {
                calName.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor(PRIVATE_EVENT_COLOR)));
            } catch (Exception e) {}

            showParticipants(event.getDescription(), participantsView);

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

            participantsView.setVisibility(View.GONE);
        }

        // VIS ARRANGØR ALLTID
        showOrganizer(event.getDescription(), organizerView);

        // --- BESKRIVELSE OG LENKER ---
        if (!event.getDescription().isEmpty()) {
            String cleanDesc = event.getDescription()
                    .replaceAll("#varsel:[\\d,]+", "")
                    .replaceAll("#deltakere:[^\\s]+", "")
                    .replaceAll("#arrangor:.+", "") // Fjern arrangør fra brødtekst
                    .trim();

            if (!cleanDesc.isEmpty()) {
                desc.setText(Html.fromHtml(cleanDesc, Html.FROM_HTML_MODE_COMPACT));
                Linkify.addLinks(desc, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES | Linkify.PHONE_NUMBERS);
                desc.setMovementMethod(LinkMovementMethod.getInstance());
                desc.setVisibility(View.VISIBLE);
            } else {
                desc.setVisibility(View.GONE);
            }
        } else {
            desc.setVisibility(View.GONE);
        }

        // --- ADRESSE OG KART ---
        if (!event.getLocation().isEmpty()) {
            loc.setText(event.getLocation());
            loc.setVisibility(View.VISIBLE);
            loc.setOnClickListener(v -> {
                String location = event.getLocation();
                Uri gmmIntentUri = Uri.parse("geo:0,0?q=" + Uri.encode(location));
                Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
                mapIntent.setPackage("com.google.android.apps.maps");
                try {
                    startActivity(mapIntent);
                } catch (Exception e) {
                    mapIntent.setPackage(null);
                    try {
                        startActivity(mapIntent);
                    } catch (Exception ex) {
                        Toast.makeText(getContext(), "Fant ingen kart-app", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } 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 showParticipants(String rawDescription, TextView view) {
        if (rawDescription == null) return;
        Matcher m = Pattern.compile("#deltakere:([^\\s]+)").matcher(rawDescription);
        if (m.find()) {
            String allEmails = m.group(1);
            String[] emails = allEmails.split(",");
            StringBuilder sb = new StringBuilder();
            sb.append("<b>Synlig for:</b><br/>");
            for (String email : emails) {
                sb.append("• ").append(email.trim()).append("<br/>");
            }
            view.setText(Html.fromHtml(sb.toString(), Html.FROM_HTML_MODE_COMPACT));
            view.setVisibility(View.VISIBLE);
        }
    }

    // NYTT: Vis arrangør
    private void showOrganizer(String rawDescription, TextView view) {
        if (rawDescription == null) return;
        Matcher m = Pattern.compile("#arrangor:(.+)").matcher(rawDescription);
        if (m.find()) {
            String organizer = m.group(1).trim();
            view.setText("Invitert av: " + organizer);
            view.setVisibility(View.VISIBLE);
        } else {
            view.setVisibility(View.GONE);
        }
    }

    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();
                    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();
            }
        });
    }
}