package com.kbs.kbsintranett;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
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 HandbookDetailFragment extends Fragment {

    private int pageId;
    private String pageTitle;
    private WebView webView;
    private ProgressBar progressBar;

    // --- CSS: DESIGN MED MER LUFT ---
    private static final String CSS_STYLE =
            "<style>" +
                    "body { font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; color: #333333; line-height: 1.6; padding: 16px; margin: 0; }" +

                    "h1 { color: #0069B3; font-size: 24px; border-bottom: 2px solid #0069B3; padding-bottom: 10px; margin-top: 0; }" +
                    "p, ul, li { margin-bottom: 12px; }" +
                    "a { color: #0069B3; font-weight: bold; text-decoration: none; }" +

                    // --- BOKSEN ---
                    ".trekkspill { " +
                    "   background-color: #fff; " +
                    "   border: 1px solid #ddd; " +
                    "   border-radius: 4px; " +
                    "   max-height: 58px; " + // LUKKET
                    "   overflow: hidden; " +
                    "   transition: max-height 0.4s ease; " +

                    // LUFT OG AVSTAND
                    "   margin-top: 32px; " +
                    "   margin-bottom: 16px; " +
                    "}" +

                    // --- KNAPPEN ---
                    ".trekkspill > a[id^='fl-accordion--label-'] { " +
                    "   display: flex; " +
                    "   justify-content: space-between; " +
                    "   align-items: center; " +
                    "   background-color: #f2f2f2; " +
                    "   color: #0069B3; " +
                    "   padding: 15px; " +
                    "   font-weight: bold; " +
                    "   cursor: pointer; " +
                    "   width: 100%; " +
                    "   height: 58px; " +
                    "   box-sizing: border-box; " +
                    "   pointer-events: auto; " +
                    "}" +

                    // --- PLUSS-TEGN ---
                    ".trekkspill > a[id^='fl-accordion--label-']::after { " +
                    "   content: '+'; " +
                    "   font-size: 24px; " +
                    "   font-weight: bold; " +
                    "   color: #0069B3; " +
                    "}" +

                    // --- ÅPEN TILSTAND ---
                    ".trekkspill.open { " +
                    "   max-height: 4000px; " + // ÅPEN
                    "   overflow: visible; " +
                    "   border-color: #0069B3; " +
                    "}" +

                    ".trekkspill.open > a[id^='fl-accordion--label-'] { " +
                    "   background-color: #0069B3; " +
                    "   color: #ffffff; " +
                    "}" +

                    ".trekkspill.open > a[id^='fl-accordion--label-']::after { " +
                    "   content: '-'; " +
                    "   color: #ffffff; " +
                    "}" +

                    // --- RYDDEJOBB ---
                    ".trekkspill > a[id^='fl-accordion--icon-'] { display: none !important; }" +
                    ".trekkspill > h2 { display: none; }" +
                    ".trekkspill > p, .trekkspill > ul, .trekkspill > div { padding: 10px 15px; }" +

                    "</style>";

    // --- JAVASCRIPT: AUTOSCROLL ---
    private static final String JS_SCRIPT =
            "<script>" +
                    "document.onclick = function(e) {\n" +
                    "    var target = e.target.closest('a[id^=\"fl-accordion--label-\"]');\n" +
                    "    \n" +
                    "    if (target) {\n" +
                    "        e.preventDefault();\n" +
                    "        \n" +
                    "        var currentBox = target.closest('.trekkspill');\n" +
                    "        \n" +
                    "        if (currentBox) {\n" +
                    "            var wasOpen = currentBox.classList.contains('open');\n" +
                    "            \n" +
                    "            // LUKK ALLE ANDRE\n" +
                    "            var allOpenBoxes = document.querySelectorAll('.trekkspill.open');\n" +
                    "            allOpenBoxes.forEach(function(box) {\n" +
                    "                box.classList.remove('open');\n" +
                    "            });\n" +
                    "            \n" +
                    "            // ÅPNE DEN VALGTE\n" +
                    "            if (!wasOpen) {\n" +
                    "                currentBox.classList.add('open');\n" +
                    "                \n" +
                    "                // AUTOSCROLL: Økt til 300ms for å vente på CSS-animasjonen\n" +
                    "                setTimeout(function() {\n" +
                    "                    currentBox.scrollIntoView({behavior: 'smooth', block: 'start'});\n" +
                    "                }, 300);\n" +
                    "            }\n" +
                    "        }\n" +
                    "        return false;\n" +
                    "    }\n" +
                    "};" +
                    "</script>";

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

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

        if (getArguments() != null) {
            pageId = getArguments().getInt("page_id");
            pageTitle = getArguments().getString("page_title");
        }

        Toolbar toolbar = view.findViewById(R.id.detail_toolbar);
        toolbar.setTitle(pageTitle != null ? pageTitle : "Håndbok");
        toolbar.setNavigationOnClickListener(v -> Navigation.findNavController(view).navigateUp());

        webView = view.findViewById(R.id.detail_webview);
        progressBar = view.findViewById(R.id.detail_loading);

        setupWebView();
        fetchContent();
    }

    private void setupWebView() {
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return handleLinkClick(request.getUrl().toString());
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return handleLinkClick(url);
            }
        });
    }

    private boolean handleLinkClick(String url) {
        // Ignorer klikk på accordion-lenker
        if (url.endsWith("#")) return true;

        String lowerUrl = url.toLowerCase();
        int formIdToOpen = 0;

        // --- SPESIALHÅNDTERING: Link til Skjemaer basert på URL-nøkkelord ---

        // ID 1: Ansatteopplysninger
        if (lowerUrl.contains("ansatteopplysninger")) {
            formIdToOpen = 1;
        }
        // ID 2: Vernerunde
        else if (lowerUrl.contains("vernerunde")) {
            formIdToOpen = 2;
        }
        // ID 4: RUH (Rapport om uønsket hendelse)
        else if (lowerUrl.contains("uonsket-hendelse") || lowerUrl.contains("/ruh")) {
            formIdToOpen = 4;
        }
        // ID 5: Lån av verktøy/henger
        else if (lowerUrl.contains("lan-av") || lowerUrl.contains("verktoy")) {
            formIdToOpen = 5;
        }
        // ID 6: Avviksmelding
        else if (lowerUrl.contains("avviksmelding") || lowerUrl.contains("/avvik")) {
            formIdToOpen = 6;
        }
        // ID 9: Sikkerhetskurs / Kompetansebevis
        else if (lowerUrl.contains("sikkerhetskurs") || lowerUrl.contains("kompetansebevis")) {
            formIdToOpen = 9;
        }
        // ID 10: HMS Bekreftelse
        else if (lowerUrl.contains("hms-bekreftelse") || lowerUrl.contains("hms-policy")) {
            formIdToOpen = 10;
        }
        // ID 11: Egenmelding
        else if (lowerUrl.contains("egenmelding")) {
            formIdToOpen = 11;
        }
        // ID 12: Sjekkliste firmabil
        else if (lowerUrl.contains("sjekkliste") && (lowerUrl.contains("bil") || lowerUrl.contains("kjoretoy"))) {
            formIdToOpen = 12;
        }
        // ID 14: SJA (Sikker Jobbanalyse)
        else if (lowerUrl.contains("sja") || lowerUrl.contains("jobbanalyse")) {
            formIdToOpen = 14;
        }
        // ID 15: Fraværsvarsel
        else if (lowerUrl.contains("fravaersvarsel") || lowerUrl.contains("fravarsvarsel")) {
            formIdToOpen = 15;
        }
        // ID 16: Refusjon utlegg
        else if (lowerUrl.contains("refusjon") || lowerUrl.contains("utlegg")) {
            formIdToOpen = 16;
        }
        // ID 21: Medarbeidersamtale
        else if (lowerUrl.contains("medarbeidersamtale")) {
            formIdToOpen = 21;
        }
        // ID 22: Medarbeiderundersøkelse
        else if (lowerUrl.contains("medarbeiderundersokelse")) {
            formIdToOpen = 22;
        }

        // Hvis vi fant et skjema, naviger dit internt
        if (formIdToOpen > 0) {
            Bundle bundle = new Bundle();
            bundle.putInt("formId", formIdToOpen);
            Navigation.findNavController(getView()).navigate(R.id.action_handbook_to_form, bundle);
            return true;
        }

        // --- STANDARD INTERN NAVIGASJON ---
        if (url.contains("intranet.kbs.no") || url.startsWith("/")) {
            int targetId = extractIdFromUrl(url);
            if (targetId > 0) {
                navigateToPage(targetId, "Laster...");
                return true;
            }

            progressBar.setVisibility(View.VISIBLE);
            RetrofitClient.getApiService().lookupPageId(url).enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                    if (!isAdded()) return;
                    progressBar.setVisibility(View.GONE);

                    if (response.isSuccessful() && response.body() != null) {
                        int id = response.body().get("id").getAsInt();
                        if (id > 0) {
                            navigateToPage(id, "Laster...");
                        } else {
                            openExternal(url);
                        }
                    } else {
                        openExternal(url);
                    }
                }

                @Override
                public void onFailure(Call<JsonObject> call, Throwable t) {
                    if (!isAdded()) return;
                    progressBar.setVisibility(View.GONE);
                    openExternal(url);
                }
            });
            return true;
        } else {
            // Ekstern lenke
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(browserIntent);
            return true;
        }
    }

    private void navigateToPage(int id, String title) {
        Bundle bundle = new Bundle();
        bundle.putInt("page_id", id);
        bundle.putString("page_title", title);
        Navigation.findNavController(getView()).navigate(R.id.action_handbook_to_detail, bundle);
    }

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

    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 fetchContent() {
        progressBar.setVisibility(View.VISIBLE);
        RetrofitClient.getApiService().getHandbookPage(pageId).enqueue(new Callback<HandbookPage>() {
            @Override
            public void onResponse(Call<HandbookPage> call, Response<HandbookPage> response) {
                if (!isAdded()) return;
                progressBar.setVisibility(View.GONE);

                if (response.isSuccessful() && response.body() != null) {
                    HandbookPage page = response.body();

                    if (getView() != null) {
                        Toolbar toolbar = getView().findViewById(R.id.detail_toolbar);
                        if (toolbar != null) toolbar.setTitle(page.title);
                    }

                    String htmlContent = "<!DOCTYPE html><html><head>" +
                            "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">" +
                            CSS_STYLE +
                            JS_SCRIPT +
                            "</head><body>";

                    htmlContent += "<h1>" + page.title + "</h1>";

                    if (page.content != null) {
                        htmlContent += page.content;
                    } else {
                        htmlContent += "<p>Ingen innhold funnet.</p>";
                    }
                    htmlContent += "</body></html>";

                    webView.loadDataWithBaseURL("https://intranet.kbs.no", htmlContent, "text/html", "UTF-8", null);

                } else {
                    Toast.makeText(getContext(), "Kunne ikke laste innhold.", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<HandbookPage> call, Throwable t) {
                if (!isAdded()) return;
                progressBar.setVisibility(View.GONE);
                Toast.makeText(getContext(), "Nettverksfeil", Toast.LENGTH_SHORT).show();
            }
        });
    }
}