/*
 * @Copyright 2018-2026 HardBackNutter
 * @License GNU General Public License
 *
 * This file is part of NeverTooManyBooks.
 *
 * NeverTooManyBooks is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * NeverTooManyBooks is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with NeverTooManyBooks. If not, see <http://www.gnu.org/licenses/>.
 */

package com.hardbacknutter.nevertoomanybooks.settings.tags;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import com.hardbacknutter.nevertoomanybooks.BaseFragment;
import com.hardbacknutter.nevertoomanybooks.R;
import com.hardbacknutter.nevertoomanybooks.settings.SettingsOutput;
import com.hardbacknutter.nevertoomanybooks.entities.Tag;
import com.hardbacknutter.nevertoomanybooks.settings.Prefs;
import com.hardbacknutter.util.insets.InsetsListenerBuilder;
import com.hardbacknutter.util.insets.Side;

public class TagAdminFragment
        extends BaseFragment {

    /** View Binding with the ViewPager2. */
    private ViewPager2 viewPager;

    private TabAdapter tabAdapter;
    private boolean animationEnabled;

    private TagAdminViewModel vm;

    /** Set the hosting Activity result, and close it. */
    private final OnBackPressedCallback backPressedCallback =
            new OnBackPressedCallback(true) {
                @Override
                public void handleOnBackPressed() {
                    //noinspection DataFlowIssue
                    new SettingsOutput(false, vm.isModified())
                            .finishActivityAndSend(getActivity());
                }
            };

    @Override
    public void onCreate(@Nullable final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //noinspection DataFlowIssue
        vm = new ViewModelProvider(getActivity()).get(TagAdminViewModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull final LayoutInflater inflater,
                             @Nullable final ViewGroup container,
                             @Nullable final Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_edit_tags, container, false);
        // pager == view; but keep it future-proof
        viewPager = view.findViewById(R.id.pager);
        return view;
    }

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

        //noinspection DataFlowIssue
        getActivity().getOnBackPressedDispatcher()
                     .addCallback(getViewLifecycleOwner(), backPressedCallback);

        final Toolbar toolbar = getToolbar();
        InsetsListenerBuilder.apply(toolbar);
        // Effectively disable edge-to-edge for the pager and include system gestures.
        new InsetsListenerBuilder(view)
                .padding(Side.Start, Side.End, Side.Bottom)
                .systemBars()
                .displayCutout()
                .systemGestures()
                .apply();

        toolbar.setTitle(R.string.lbl_tags);
        toolbar.setSubtitle("");

        tabAdapter = new TabAdapter(getActivity());
        final TabLayout tabPanel = getActivity().findViewById(R.id.tab_panel);

        // We do NOT want any page recycled/reused - hence cache/keep ALL pages.
        viewPager.setOffscreenPageLimit(tabAdapter.getItemCount());

        viewPager.setAdapter(tabAdapter);
        //noinspection DataFlowIssue
        animationEnabled = Prefs.isAnimationEnabled(getContext());
        new TabLayoutMediator(tabPanel, viewPager, false, animationEnabled, (tab, position) ->
                tab.setText(getString(tabAdapter.getTabTitle(position)))).attach();
    }

    /**
     * Called from {@link TagEditorFragment}.
     *
     * @param tag for we want to create a new mapping (or edit existing).
     */
    void editOrCreateMapping(@NonNull final Tag tag) {
        viewPager.setCurrentItem(1, animationEnabled);

        getParentFragmentManager()
                .getFragments()
                .stream()
                .filter(f -> f instanceof TagMappingEditorFragment)
                .findFirst()
                .ifPresent(f -> ((TagMappingEditorFragment) f)
                        .editOrCreateMapping(tag));
    }

    /**
     * All the tabs that will be shown.
     * <p>
     * Limited amount of Fragments, no need/desire to use ExtFragmentStateAdapter.F
     */
    private static class TabAdapter
            extends FragmentStateAdapter {

        static final String ERROR_POSITION = "position=";

        /**
         * Constructor.
         *
         * @param activity the hosting activity
         */
        TabAdapter(@NonNull final FragmentActivity activity) {
            super(activity);
        }

        @Override
        public int getItemCount() {
            return 2;
        }


        @NonNull
        @Override
        public Fragment createFragment(final int position) {
            switch (position) {
                case 0:
                    return new TagEditorFragment();
                case 1:
                    return new TagMappingEditorFragment();
            }
            throw new IllegalArgumentException(ERROR_POSITION + position);
        }

        @StringRes
        int getTabTitle(final int position) {
            switch (position) {
                case 0:
                    return R.string.lbl_tags;
                case 1:
                    return R.string.lbl_substitutions;
            }
            throw new IllegalArgumentException(ERROR_POSITION + position);
        }
    }
}
