/*
 * @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.searchsites;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
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.core.view.MenuProvider;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

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

import java.util.List;

import com.hardbacknutter.nevertoomanybooks.BaseFragment;
import com.hardbacknutter.nevertoomanybooks.R;
import com.hardbacknutter.nevertoomanybooks.core.widgets.ScreenSize;
import com.hardbacknutter.nevertoomanybooks.dialogs.Tip;
import com.hardbacknutter.nevertoomanybooks.dialogs.TipManager;
import com.hardbacknutter.nevertoomanybooks.searchengines.Site;
import com.hardbacknutter.nevertoomanybooks.settings.Prefs;
import com.hardbacknutter.util.insets.InsetsListenerBuilder;
import com.hardbacknutter.util.insets.Side;

public class SearchAdminFragment
        extends BaseFragment {

    private TabAdapter tabAdapter;

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

    private final OnBackPressedCallback backPressedCallback =
            new OnBackPressedCallback(true) {
                @Override
                public void handleOnBackPressed() {
                    final boolean hasSites = vm.validate();
                    if (hasSites) {
                        // 2022-05-29: we now always persist.
                        vm.persist();
                        // but to keep changes minimal, we still return the list if it's single.
                        if (vm.getTypes().size() == 1) {
                            //noinspection DataFlowIssue
                            new SingleSiteListInputOutput(vm.getList(vm.getTypes().get(0)))
                                    .finishActivityAndSend(getActivity());
                            return;
                        }
                        // all types, nothing to return
                        //noinspection DataFlowIssue
                        getActivity().setResult(Activity.RESULT_OK, null);
                        getActivity().finish();

                    } else {
                        Snackbar.make(viewPager, R.string.warning_enable_at_least_1_website,
                                      Snackbar.LENGTH_LONG).show();
                    }
                }
            };

    private TabLayout tabPanel;

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

        //noinspection DataFlowIssue
        vm = new ViewModelProvider(getActivity()).get(SearchAdminViewModel.class);
        vm.init(SingleSiteListInputOutput.fromBundle(getArguments()));
    }

    @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_search_sites, 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);
        // Effectively disable edge-to-edge for the pager
        // Do NOT include systemGestures as this will cause the content to be squeezed.
        new InsetsListenerBuilder(view)
                .padding(Side.Start, Side.End, Side.Bottom)
                .systemBars()
                .displayCutout()
                .apply();

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

        final Toolbar toolbar = getToolbar();
        toolbar.setTitle(R.string.lbl_websites);
        toolbar.setSubtitle("");

        toolbar.addMenuProvider(new ToolbarMenuProvider(), getViewLifecycleOwner(),
                                Lifecycle.State.RESUMED);

        tabAdapter = new TabAdapter(getActivity(), vm.getTypes());
        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
        final boolean animationEnabled = Prefs.isAnimationEnabled(getContext());
        new TabLayoutMediator(tabPanel, viewPager, false, animationEnabled, (tab, position) -> {
            if (ScreenSize.compute(getActivity()).getWidth() == ScreenSize.Value.Compact) {
                tab.setText(getString(tabAdapter.getTabTitle(position)));
            } else {
                // ScreenSize.Value.Medium and up
                tab.setText(getString(tabAdapter.getTabDescription(position)));
            }
            // 2024-05-07: this turned out to be a dud...
            // it's not shown when long-pressing the tab?
            tab.setContentDescription(getString(tabAdapter.getTabDescription(position)));
        }).attach();

        if (savedInstanceState == null) {
            TipManager.getInstance().show(getContext(), Tip.CONFIGURE_SITES);
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        if (vm.getTypes().size() == 1) {
            tabPanel.setVisibility(View.GONE);
        } else {
            tabPanel.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 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 {

        @NonNull
        private final List<Site.Type> siteTypeList;

        /**
         * Constructor.
         *
         * @param activity the hosting Activity
         * @param types    the list of tabs (types) to be shown
         */
        TabAdapter(@NonNull final FragmentActivity activity,
                   @NonNull final List<Site.Type> types) {
            super(activity);
            siteTypeList = types;
        }

        @Override
        public int getItemCount() {
            return siteTypeList.size();
        }

        @NonNull
        @Override
        public Fragment createFragment(final int position) {
            return SearchOrderFragment.create(siteTypeList.get(position));
        }

        @StringRes
        int getTabTitle(final int position) {
            return siteTypeList.get(position).getLabelResId();
        }

        @StringRes
        int getTabDescription(final int position) {
            return siteTypeList.get(position).getContentDescriptionResId();
        }
    }

    private final class ToolbarMenuProvider
            implements MenuProvider {

        @Override
        public void onCreateMenu(@NonNull final Menu menu,
                                 @NonNull final MenuInflater menuInflater) {
            menu.add(Menu.NONE, R.id.MENU_ACTION_CLEAR, 0, R.string.action_clear)
                .setIcon(R.drawable.check_box_outline_blank_24px)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

            menu.add(Menu.NONE, R.id.MENU_RESET, 0, R.string.action_reset_to_default)
                .setIcon(R.drawable.undo_24px)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        }

        @SuppressLint("NotifyDataSetChanged")
        @Override
        public boolean onMenuItemSelected(@NonNull final MenuItem menuItem) {
            final int menuItemId = menuItem.getItemId();
            if (menuItemId == R.id.MENU_ACTION_CLEAR) {
                // See TabAdapter: the position will always match the index of the type
                final int position = viewPager.getCurrentItem();
                vm.clear(vm.getTypes().get(position));
                return true;

            } else if (menuItemId == R.id.MENU_RESET) {
                // See TabAdapter: the position will always match the index of the type
                final int position = viewPager.getCurrentItem();
                //noinspection DataFlowIssue
                vm.reset(getContext(), vm.getTypes().get(position));
                return true;
            }

            return false;
        }
    }
}
