// FILSTI: app\src\main\java\com\kbs\kbsintranett\InternalLinkMovementMethod.java
package com.kbs.kbsintranett;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle; // <-- Sjekk at denne er med!
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.text.style.URLSpan;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.navigation.Navigation;

import com.google.gson.JsonObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

public class InternalLinkMovementMethod extends LinkMovementMethod {
    private static InternalLinkMovementMethod instance;
    private static final String TAG = "InternalLinkMethod";

    public static InternalLinkMovementMethod getInstance() {
        if (instance == null) instance = new InternalLinkMovementMethod();
        return instance;
    }

    @Override
    public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
        int action = event.getAction();

        if (action == MotionEvent.ACTION_UP) {
            int x = (int) event.getX();
            int y = (int) event.getY();

            x -= widget.getTotalPaddingLeft();
            y -= widget.getTotalPaddingTop();

            x += widget.getScrollX();
            y += widget.getScrollY();

            int line = widget.getLayout().getLineForVertical(y);
            int off = widget.getLayout().getOffsetForHorizontal(line, x);

            URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
            if (link.length != 0) {
                String url = link[0].getURL();
                handleLink(widget.getContext(), url, widget);
                return true;
            }
        }
        return super.onTouchEvent(widget, buffer, event);
    }

    private void handleLink(Context context, String url, View view) {
        Log.d(TAG, "Link clicked: " + url);

        // 1. Sjekk om det er en intern lenke
        if (url.contains("intranet.kbs.no") || url.startsWith("/")) {

            // a) Prøv å finne ID hvis den finnes i URLen (?p=123)
            int pageId = extractIdFromUrl(url);

            if (pageId > 0) {
                navigateToInternalPage(view, pageId, "Laster...");
            } else {
                // b) Det er en "pen" URL. Vi må spørre APIet hva IDen er.
                // Vi bruker Toast for å gi feedback om at noe skjer
                Toast.makeText(context, "Åpner side...", Toast.LENGTH_SHORT).show();

                RetrofitClient.getApiService().lookupPageId(url).enqueue(new Callback<JsonObject>() {
                    @Override
                    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            int id = response.body().get("id").getAsInt();
                            if (id > 0) {
                                // Suksess! Naviger internt
                                navigateToInternalPage(view, id, "Laster...");
                            } else {
                                // Fant ikke ID, åpne i WebView som fallback
                                openInWebView(context, url);
                            }
                        } else {
                            openInWebView(context, url);
                        }
                    }

                    @Override
                    public void onFailure(Call<JsonObject> call, Throwable t) {
                        openInWebView(context, url);
                    }
                });
            }
        } else {
            // Ekstern lenke - åpne i nettleser
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            context.startActivity(browserIntent);
        }
    }

    private int extractIdFromUrl(String url) {
        Pattern p = Pattern.compile("[?&](p|page_id|post)=([0-9]+)");
        Matcher m = p.matcher(url);
        if (m.find()) {
            try {
                return Integer.parseInt(m.group(2));
            } catch (NumberFormatException e) {
                return 0;
            }
        }
        return 0;
    }

    private void navigateToInternalPage(View view, int pageId, String title) {
        try {
            Bundle bundle = new Bundle();
            bundle.putInt("page_id", pageId);
            bundle.putString("page_title", title);
            Navigation.findNavController(view).navigate(R.id.action_handbook_to_detail, bundle);
        } catch (Exception e) {
            Log.e(TAG, "Kunne ikke navigere", e);
        }
    }

    private void openInWebView(Context context, String url) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra(WebViewActivity.EXTRA_URL, url);
        intent.putExtra(WebViewActivity.EXTRA_TITLE, "KBS Intranett");
        context.startActivity(intent);
    }
}