package com.kbs.kbsintranett;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import com.bumptech.glide.Glide;

public class NewsDetailFragment extends Fragment {

    // CSS Styling (Samme stil som håndboken, pluss bildehåndtering)
    private static final String CSS_STYLE =
            "<style>" +
                    "body { font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; color: #333333; line-height: 1.6; padding: 0; margin: 0; }" +
                    "p, ul, li { margin-bottom: 12px; font-size: 16px; }" +
                    "a { color: #0069B3; font-weight: bold; text-decoration: none; }" +
                    "h1, h2, h3 { color: #0069B3; margin-top: 20px; margin-bottom: 10px; }" +

                    // Bilde-styling
                    "img { " +
                    "  max-width: 100% !important; " +
                    "  height: auto !important; " +
                    "  border-radius: 4px; " +
                    "  margin: 16px 0; " +
                    "  box-shadow: 0 2px 5px rgba(0,0,0,0.1); " +
                    "  display: block;" +
                    "}" +

                    // Fjerner unødvendig whitespace fra WP-galleri
                    ".gallery-item { margin: 0; padding: 0; }" +
                    "</style>";

    // JavaScript for å fange opp bildeklikk
    private static final String JS_SCRIPT =
            "<script>" +
                    "document.addEventListener('DOMContentLoaded', function() {" +
                    "   var images = document.getElementsByTagName('img');" +
                    "   for (var i = 0; i < images.length; i++) {" +
                    "       images[i].onclick = function() {" +
                    "           Android.showImage(this.src);" +
                    "       }" +
                    "   }" +
                    "});" +
                    "</script>";

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

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

        if (getArguments() != null) {
            WpPost post = (WpPost) getArguments().getSerializable("post_data");
            if (post != null) {
                setupViews(view, post);
            }
        }
    }

    private void setupViews(View view, WpPost post) {
        Toolbar toolbar = view.findViewById(R.id.detail_toolbar);
        toolbar.setNavigationOnClickListener(v -> Navigation.findNavController(view).navigateUp());

        ImageView image = view.findViewById(R.id.detail_image);
        TextView title = view.findViewById(R.id.detail_title);
        TextView category = view.findViewById(R.id.detail_category);
        TextView date = view.findViewById(R.id.detail_date);
        TextView author = view.findViewById(R.id.detail_author);
        WebView webView = view.findViewById(R.id.detail_webview);

        // Header bilde
        String imgUrl = post.getFeaturedImageUrl();
        if (imgUrl != null) {
            Glide.with(this).load(imgUrl).centerCrop().into(image);
        } else {
            image.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));
        }

        title.setText(post.getTitleStr());
        category.setText(post.getCategoryName());
        date.setText("Publisert: " + post.date);
        author.setText("Av: " + post.getAuthorName());

        // Konfigurer WebView
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);

        // Legg til Interface for å snakke med Java
        webView.addJavascriptInterface(new WebAppInterface(getContext()), "Android");

        // Håndter linker internt (som i Håndboken)
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // Bruk samme link-logikk som i Håndboken hvis nødvendig,
                // men her lar vi linker åpnes i nettleser for enkelhets skyld foreløpig
                return false;
            }
        });

        // Bygg HTML
        String rawContent = post.getContentStr();

        // Vask innholdet litt hvis nødvendig (f.eks fjerne inline styles som ødelegger)
        // Her legger vi bare til vår CSS og JS
        String htmlData = "<!DOCTYPE html><html><head>" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">" +
                CSS_STYLE +
                JS_SCRIPT +
                "</head><body>" +
                rawContent +
                "</body></html>";

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

    // Bridge-klasse for å ta imot klikk fra JavaScript
    public class WebAppInterface {
        Context mContext;

        WebAppInterface(Context c) {
            mContext = c;
        }

        @JavascriptInterface
        public void showImage(String url) {
            // Må kjøres på UI-tråden
            if (getActivity() != null) {
                getActivity().runOnUiThread(() -> {
                    ImageDialogFragment dialog = ImageDialogFragment.newInstance(url);
                    dialog.show(getParentFragmentManager(), "image_lightbox");
                });
            }
        }
    }
}