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

        swipeRefreshLayout.setOnRefreshListener(this::fetchFormsList);

        // Første gangs lasting
        swipeRefreshLayout.setRefreshing(true);
        fetchFormsList();

        return view;
    }

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

                if (response.isSuccessful() && response.body() != null) {
                    List<GravityForm> activeForms = new ArrayList<>();
                    for (GravityForm form : response.body()) {
                        if (form.getIsActive()) {
                            // HMS-bekreftelse (10) og Refusjon-vedlegg (18) skal ikke i listen
                            if (form.id != 10 && form.id != 18) {
                                activeForms.add(form);
                            }
                        }
                    }

                    Collections.sort(activeForms, (f1, f2) ->
                            Integer.compare(extractNumber(f1.title), extractNumber(f2.title)));

                    populateList(activeForms);

                } else {
                    if (response.code() == 401 || response.code() == 403) {
                        showError("Sesjonen utløp, men er nå reparert. Vennligst sveip ned for å prøve igjen.");
                    } else {
                        showError("Kunne ikke hente skjemaer. Kode: " + response.code());
                    }
                }
            }

            @Override
            public void onFailure(Call<List<GravityForm>> call, Throwable t) {
                if (!isAdded()) return;
                swipeRefreshLayout.setRefreshing(false);
                showError("Nettverksfeil: Prøv igjen.");
            }
        });
    }

    private void populateList(List<GravityForm> forms) {
        formsContainer.removeAllViews();
        if (forms.isEmpty()) {
            showError("Ingen aktive skjemaer funnet.");
            return;
        }

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

    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.parseColor("#C40426")); // KBS Rød
        tv.setTextSize(16);
        tv.setGravity(Gravity.CENTER);
        tv.setPadding(40, 100, 40, 40);
        formsContainer.addView(tv);
    }

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

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