package it.integry.integrywmsnative.gest.prod_rientro_merce;

import android.content.Context;
import android.os.Bundle;
import android.text.SpannableString;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableField;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import it.integry.integrywmsnative.MainApplication;
import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.barcode_reader.BarcodeManager;
import it.integry.integrywmsnative.core.expansion.BaseFragment;
import it.integry.integrywmsnative.core.interfaces.ILifecycleFragment;
import it.integry.integrywmsnative.core.interfaces.IScrollableFragment;
import it.integry.integrywmsnative.core.interfaces.ITitledFragment;
import it.integry.integrywmsnative.core.model.MtbColr;
import it.integry.integrywmsnative.databinding.FragmentProdRientroMerceBinding;
import it.integry.integrywmsnative.gest.prod_rientro_merce.order_detail.ProdRientroMerceOrderDetailFragment;
import it.integry.integrywmsnative.gest.prod_rientro_merce.order_list.ProdRientroMerceOrderListFragment;
import it.integry.integrywmsnative.gest.prod_versamento_materiale.dto.OrdineLavorazioneDTO;
import it.integry.integrywmsnative.ui.ElevatedToolbar;
import it.integry.integrywmsnative.view.bottom_sheet__lu_content.BottomSheetFragmentLUContentView;
import it.integry.integrywmsnative.view.bottom_sheet__mtb_colr_edit.BottomSheetMtbColrEditView;
import it.integry.integrywmsnative.view.dialogs.base.DialogSimpleMessageView;

public class ProdRientroMerceFragment extends BaseFragment implements
        ITitledFragment,
        IScrollableFragment,
        ILifecycleFragment,
        ProdRientroMerceViewModel.Listener,
        BottomSheetFragmentLUContentView.Listener,
        BottomSheetMtbColrEditView.Listener,
        ProdRientroMerceOrderListFragment.OnRefreshListener {


    public final ObservableField<Boolean> isLargeLayout = new ObservableField<>(false);

    @Inject
    ProdRientroMerceViewModel mViewModel;

    private AppCompatTextView mAppBarTitle;
    private final List<Runnable> mOnPreDestroyList = new ArrayList<>();

    private FragmentProdRientroMerceBinding mBindings;

    private ProdRientroMerceOrderListFragment mProdRientroMerceOrderListFragment;
    private ProdRientroMerceOrderDetailFragment mProdRientroMerceOrderDetailFragment;
    private ElevatedToolbar mToolbar;

    public static ProdRientroMerceFragment newInstance() {
        return new ProdRientroMerceFragment();
    }



    @Override
    public void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);

        boolean isLargeLayout = getResources().getBoolean(R.bool.large_layout);
        this.isLargeLayout.set(isLargeLayout);

        mProdRientroMerceOrderListFragment = ProdRientroMerceOrderListFragment.newInstance(mToolbar);
        mProdRientroMerceOrderDetailFragment = ProdRientroMerceOrderDetailFragment.newInstance();



        mProdRientroMerceOrderListFragment
                .setOnItemSelectedRunnable(order -> {
                    if (!isLargeLayout) {
                        getChildFragmentManager()
                                .beginTransaction()
                                .show(mProdRientroMerceOrderDetailFragment)
                                .addToBackStack(ProdRientroMerceOrderDetailFragment.class.getName())
                                .commit();
                    }

                    mProdRientroMerceOrderDetailFragment.setOrder(order);
                })
                .setOnRefreshListener(this);
        mProdRientroMerceOrderDetailFragment.setOnMtbColtClicked(item -> {
            mBindings.bottomSheetMtbColrEdit.setMtbColr(item.getMtbColr().get(0));
            mBindings.bottomSheetMtbColrEdit.expand();
        });

        if (isLargeLayout) {
            getChildFragmentManager()
                    .beginTransaction()
                    .replace(R.id.left_side_fragment_container, mProdRientroMerceOrderListFragment)
                    .replace(R.id.right_side_fragment_container, mProdRientroMerceOrderDetailFragment)
                    .commit();
        } else {
            getChildFragmentManager()
                    .beginTransaction()
                    .add(R.id.full_width_container, mProdRientroMerceOrderListFragment)
                    .add(R.id.full_width_container, mProdRientroMerceOrderDetailFragment)
                    .hide(mProdRientroMerceOrderDetailFragment)
                    .commit();
        }


        MainApplication.appComponent
                .prodRientroMerceComponent()
                .create()
                .inject(this);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        mBindings = DataBindingUtil.inflate(LayoutInflater.from(getActivity()), R.layout.fragment_prod_rientro_merce, container, false);
        mBindings.setLifecycleOwner(this);
        mBindings.setView(this);
        mBindings.setViewmodel(mViewModel);

        mViewModel.setListener(this);

        this.initBottomSheet();

        return mBindings.getRoot();
    }

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

        if (savedInstanceState == null) {
            this.mViewModel.getOrdiniLavorazioneAperti().observe(this.getViewLifecycleOwner(), this::ordersUpdated);
            mViewModel.refreshOrderList();
        }
    }


    @Override
    public void onCreateActionBar(AppCompatTextView titleText, Context context) {
        mAppBarTitle = titleText;
        mAppBarTitle.setText(context.getText(R.string.rientro_merce_fragment_title).toString());

    }

    @Override
    public void addOnPreDestroy(Runnable onPreDestroy) {
        this.mOnPreDestroyList.add(onPreDestroy);
    }

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

        for (Runnable onPreDestroy : mOnPreDestroyList) {
            onPreDestroy.run();
        }

        mProdRientroMerceOrderDetailFragment.onDetach();
        mProdRientroMerceOrderListFragment.onDetach();
    }

    @Override
    public void onDataSaved() {
    }

    private void ordersUpdated(List<OrdineLavorazioneDTO> ordiniLavorazioneList) {
        this.mProdRientroMerceOrderListFragment.pushOrderList(ordiniLavorazioneList);
    }

    @Override
    public void setScrollToolbar(ElevatedToolbar toolbar) {
        mToolbar = toolbar;
    }


    private void initBottomSheet() {
        mBindings.bottomSheetMtbColrEdit.setListener(this);
        mBindings.bottomSheetMtbColrEdit.disableEditButton();
        mBindings.bottomSheetMtbColrEdit.init(mBindings.bottomSheetMtbColrEdit, mBindings.bottomSheetMtbColrEditBackground);
    }

    @Override
    public void onMtbColrEdit(MtbColr mtbColr) {

    }

    @Override
    public void onMtbColrDelete(MtbColr mtbColr) {
        String text = getResources().getString(R.string.alert_delete_mtb_colr);
        DialogSimpleMessageView.makeWarningDialog(new SpannableString(text),
                null,
                () -> mProdRientroMerceOrderDetailFragment.deleteMtbColr(mtbColr),
                () -> {
                }
        ).show(requireActivity().getSupportFragmentManager(), "tag");
    }

    @Override
    public void onOrderLoadingStarted() {
        BarcodeManager.disable();
        this.mProdRientroMerceOrderListFragment.onOrderLoadingStarted();
    }

    @Override
    public void onOrderLoadingEnded() {
        BarcodeManager.enable();
        this.mProdRientroMerceOrderListFragment.onOrderLoadingEnded();
    }

    @Override
    public void onRefresh() {
        this.mViewModel.refreshOrderList();
    }

    @Override
    public void onPreDestroy(Runnable onComplete) {
        if(getChildFragmentManager().getBackStackEntryCount() > 0)
            getChildFragmentManager().popBackStack();

        else onComplete.run();
    }
}