package com.kbs.kbsintranett;

import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

public class FormsListFragment extends Fragment {

    private LinearLayout formsContainer;
    private ProgressBar progressBar;
    private TextView errorText;
    private SwipeRefreshLayout swipeRefreshLayout;
    private static final Pattern TITLE_NUMBER_PATTERN = Pattern.compile("^(\\d+)[.\\s-]+\\s*(.*)");

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_forms_list, container, false);

        formsContainer = view.findViewById(R.id.forms_container);
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh);

        // Opprett en ProgressBar manuelt for første gangs lasting
        progressBar = new ProgressBar(getContext());
        LinearLayout.LayoutParams progressParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        progressParams.gravity = Gravity.CENTER;
        progressBar.setLayoutParams(progressParams);

        formsContainer.addView(progressBar);

        errorText = new TextView(getContext());
        errorText.setTextColor(Color.RED);
        errorText.setVisibility(View.GONE);
        errorText.setPadding(20, 20, 20, 20);
        formsContainer.addView(errorText);

        // Sett opp listener for swipe
        swipeRefreshLayout.setOnRefreshListener(() -> {
            fetchFormsList();
        });

        // Hent data første gang
        fetchFormsList();

        return view;
    }

    private void fetchFormsList() {
        // Skjul feilmelding før ny henting
        if (errorText != null) errorText.setVisibility(View.GONE);

        RetrofitClient.getApiService().getFormsList().enqueue(new Callback<List<GravityForm>>() {
            @Override
            public void onResponse(Call<List<GravityForm>> call, Response<List<GravityForm>> response) {
                if (!isAdded()) return;

                // Stopp lasting-indikatorer
                progressBar.setVisibility(View.GONE);
                swipeRefreshLayout.setRefreshing(false);

                if (response.isSuccessful() && response.body() != null) {
                    List<GravityForm> allForms = response.body();
                    List<GravityForm> activeForms = new ArrayList<>();

                    for (GravityForm form : allForms) {
                        if (form.getIsActive()) {
                            // NYTT: Hardkodet filtrering av skjemaer som ikke skal vises i listen
                            // ID 10 = HMS-bekreftelse (Skal ligge i Håndbok/separat flyt)
                            // ID 18 = Refusjon-vedlegg (Er et underskjema som brukes av ID 16)
                            if (form.id == 10 || form.id == 18) {
                                continue;
                            }

                            activeForms.add(form);
                        }
                    }

                    Collections.sort(activeForms, new Comparator<GravityForm>() {
                        @Override
                        public int compare(GravityForm f1, GravityForm f2) {
                            int num1 = extractNumber(f1.title);
                            int num2 = extractNumber(f2.title);
                            return Integer.compare(num1, num2);
                        }
                    });
                    populateList(activeForms);

                } else {
                    String msg = "Kunne ikke hente skjemaer. Kode: " + response.code();
                    if (response.code() == 401 || response.code() == 403) {
                        msg += "\n(Mangler tilgang. Prøv å logge ut og inn igjen.)";
                    }
                    showError(msg);
                }
            }

            @Override
            public void onFailure(Call<List<GravityForm>> call, Throwable t) {
                if (!isAdded()) return;

                // Stopp lasting-indikatorer
                progressBar.setVisibility(View.GONE);
                swipeRefreshLayout.setRefreshing(false);

                showError("Nettverksfeil: " + t.getMessage());
            }
        });
    }

    private void populateList(List<GravityForm> forms) {
        formsContainer.removeAllViews();

        if (forms.isEmpty()) {
            showError("Ingen aktive skjemaer funnet.");
            return;
        }

        for (GravityForm form : forms) {
            int formId = form.id;
            String cleanTitle = cleanTitle(form.title);
            addFormButton(formsContainer, cleanTitle, formId);
        }
    }

    private void addFormButton(LinearLayout container, String title, int formId) {
        Button btn = new Button(getContext());
        btn.setText(title);
        btn.setBackgroundColor(Color.parseColor("#0069B3"));
        btn.setTextColor(Color.WHITE);
        btn.setPadding(30, 30, 30, 30);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 0, 0, 20);
        btn.setLayoutParams(params);

        btn.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putInt("formId", formId);
            Navigation.findNavController(v).navigate(R.id.action_formsListFragment_to_formsDetailFragment, bundle);
        });
        container.addView(btn);
    }

    private void showError(String message) {
        if (formsContainer == null) return;
        formsContainer.removeAllViews();

        TextView tv = new TextView(getContext());
        tv.setText(message);
        tv.setTextColor(Color.RED);
        tv.setTextSize(16);
        formsContainer.addView(tv);
    }

    private int extractNumber(String title) {
        if (title == null) return 9999;
        Matcher m = TITLE_NUMBER_PATTERN.matcher(title.trim());
        if (m.find()) {
            try {
                return Integer.parseInt(m.group(1));
            } catch (NumberFormatException e) {
                return 9999;
            }
        }
        return 9999;
    }

    private String cleanTitle(String title) {
        if (title == null) return "";
        Matcher m = TITLE_NUMBER_PATTERN.matcher(title.trim());
        if (m.find()) {
            return m.group(2);
        }
        return title;
    }
}