package it.integry.integrywmsnative.gest.inventario;

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

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatTextView;

import com.ravikoradiya.liveadapter.LiveAdapter;
import com.ravikoradiya.liveadapter.Type;

import java.util.List;

import javax.inject.Inject;

import it.integry.integrywmsnative.BR;
import it.integry.integrywmsnative.MainApplication;
import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.data_store.db.entity.InventarioRoomDTO;
import it.integry.integrywmsnative.core.expansion.BaseFragment;
import it.integry.integrywmsnative.core.expansion.RunnableArgss;
import it.integry.integrywmsnative.core.interfaces.ILifecycleFragment;
import it.integry.integrywmsnative.core.interfaces.ITitledFragment;
import it.integry.integrywmsnative.core.rest.model.inventario.InventarioArtDTO;
import it.integry.integrywmsnative.databinding.FragmentElencoInventarioBinding;
import it.integry.integrywmsnative.databinding.FragmentElencoInventarioListSingleItemBinding;
import it.integry.integrywmsnative.gest.inventario.bottom_sheet__inventario_actions.BottomSheetInventarioActionsView;
import it.integry.integrywmsnative.gest.inventario.dialogs.ask_info_inventario.DialogAskInfoInventarioView;
import it.integry.integrywmsnative.gest.inventario.picking.PickingInventarioActivity;
import it.integry.integrywmsnative.view.dialogs.yes_no.DialogYesNoView;

public class ElencoInventariFragment extends BaseFragment implements ITitledFragment, ILifecycleFragment, ElencoInventariViewModel.Listener {

    private FragmentElencoInventarioBinding mBinding;

    @Inject
    ElencoInventariViewModel mViewModel;

    private int barcodeScannerIstanceID = -1;

    public ElencoInventariFragment() {
        // Required empty public constructor
    }


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

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);

        MainApplication.appComponent
                .inventarioComponent()
                .create()
                .inject(this);

        mViewModel.setListener(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mBinding = FragmentElencoInventarioBinding.inflate(inflater, container, false);

        mBinding.setLifecycleOwner(this);
        mBinding.setViewmodel(mViewModel);

        mViewModel.loadData();
        this.initRecyclerView();

        return mBinding.getRoot();
    }

    private void initRecyclerView() {
        mViewModel.getInventarioList().observe(getViewLifecycleOwner(), data -> {
            mBinding.emptyView.setVisibility(data == null || data.isEmpty() ? View.VISIBLE : View.GONE);
        });

        var itemType = new Type<InventarioRoomDTO, FragmentElencoInventarioListSingleItemBinding>(R.layout.fragment_elenco_inventario_list_single_item, BR.item);
        itemType.onClick(x -> {

            var item = x.getBinding().getItem();

            if (!item.isSyncronized()) {
                var bottomSheetActions = new BottomSheetInventarioActionsView(item)
                        .setListener(new BottomSheetInventarioActionsView.Listener() {
                            @Override
                            public void onItemEdit() {
                                mViewModel.loadInventarioData(item.getIdInventario(), listArts -> {
                                    startPicking(item, listArts);
                                });
                            }

                            @Override
                            public void onItemDelete() {
                                deleteInventarioRequest(item);
                            }
                        });


                bottomSheetActions.show(requireActivity().getSupportFragmentManager(), "tag");
            }

            return null;
        });

        new LiveAdapter(mViewModel.getInventarioList(), this)
                .map(InventarioRoomDTO.class, itemType)
                .into(this.mBinding.inventarioList);


//        binding.swiperefresh.setRefreshing(true);
//        binding.swiperefresh.setOnRefreshListener(() -> {
//            viewModel.loadData();
//        });
    }


    @Override
    public void onPreDestroy(Runnable onComplete) {
        mViewModel.destroyData();
        onComplete.run();
    }

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

    @Override
    public void onInventarioInfoRequest(RunnableArgss<Long, String> onComplete) {
        DialogAskInfoInventarioView.newInstance(onComplete, null)
                .show(requireActivity().getSupportFragmentManager(), "tag");
    }

    @Override
    public void onInventarioLoaded(InventarioRoomDTO inventarioRoomDTO, List<InventarioArtDTO> listaArts) {
        startPicking(inventarioRoomDTO, listaArts);
    }


    private void startPicking(InventarioRoomDTO inventarioRoomDTO, List<InventarioArtDTO> listArts) {
        PickingInventarioActivity.startActivity(requireContext(), inventarioRoomDTO, listArts);
    }

    @Override
    public void onCreateInventarioRequest(long inventoryId, String zone) {
        DialogYesNoView
                .newInstance(null, "Vuoi procedere con la creazione di un nuovo inventario con codice " + inventoryId + "?",
                        dialogResponse -> {
                            switch (dialogResponse) {
                                case YES:
                                    this.mViewModel.createNewInventario(inventoryId, zone, this::startPicking);
                                    break;

                                case NO:
                                case ABORT:
                                    mViewModel.openInventario();
                                    break;
                            }
                        })
                .show(requireActivity().getSupportFragmentManager(), "tag");
    }

    public void deleteInventarioRequest(InventarioRoomDTO inventarioRoomDTO) {
        DialogYesNoView
                .newInstance(null, "Vuoi cancellare l'inventario?",
                        dialogResponse -> {
                            switch (dialogResponse) {
                                case YES:
                                    this.mViewModel.deleteInventario(inventarioRoomDTO);
                                    break;

                                case NO:
                                case ABORT:
                                    break;
                            }
                        })
                .show(requireActivity().getSupportFragmentManager(), "tag");
    }
}