package com.cygnusa.hyperm.fragments;


import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.DragEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ExpandableListView;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.cygnusa.hyperm.LoginActivity;
import com.cygnusa.hyperm.ProductFeedbackFormActivity;
import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.HyperMEnquiryForm;
import com.cygnusa.hyperm.adapter.ComparisionExpandableListAdapterNew;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.CommonMethods;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.StorePreference;
import com.cygnusa.hyperm.wrappers.ComparisonCompareDataCategory;
import com.cygnusa.hyperm.wrappers.ComparisonDataModel;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.RootGetAllComparisonModel;

import net.cachapa.expandablelayout.ExpandableLayout;

import java.util.List;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.cygnusa.hyperm.MainActivity.img_broucher;
import static com.cygnusa.hyperm.MainActivity.img_rating;
import static com.cygnusa.hyperm.MainActivity.layout1;

public class HypermComparisonFragmentNew extends Fragment implements ExpandableLayout.OnExpansionUpdateListener, View.OnClickListener {

    private TextView productNameOne;
    private TextView productNameTwo;
    private ImageView productImage, productImageOne, productImageTwo;
    private ImageButton closeButtonOne, closeButtonTwo;
    private LinearLayout headerOne, headerTwo;
    private ExpandableListView comparisionList;
    private LinearLayout dragAndDropView, itemLayout;

    private ComparisonDataModel MODELS;
    private ComparisionExpandableListAdapterNew ADAPTER;

    private List<ComparisonCompareDataCategory> comparisonOne;
    private List<ComparisonCompareDataCategory> comparisonTwo;

    private ProgressBar progressBar;
    private StorePreference storePreference;

    ApiService restService;
    private ExpandableLayout expandableLayout;
    private ImageView expandButton;
    private boolean isOpened = true;
    private ImageView imgNoData;

    private HorizontalScrollView scrollView;
    private ImageView leftArrow, rightArrow;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_comparision_new, null);
    }


    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.findViewById(R.id.backButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Objects.requireNonNull(getActivity()).onBackPressed();

            }
        });

        storePreference = new StorePreference(getActivity());
        restService = ((MainApplication) Objects.requireNonNull(getActivity()).getApplication()).getClient();

        expandableLayout = view.findViewById(R.id.expandable_layout);
        expandButton = view.findViewById(R.id.expand_button);
        expandableLayout.setOnExpansionUpdateListener(this);
        expandButton.setOnClickListener(this);
        itemLayout = view.findViewById(R.id.itemLayout);


        TextView productName = view.findViewById(R.id.productName);
        productImage = view.findViewById(R.id.productImage);

        productNameOne = view.findViewById(R.id.productNameOne);
        productImageOne = view.findViewById(R.id.productImageOne);
        closeButtonOne = view.findViewById(R.id.closeButtonOne);
        headerOne = view.findViewById(R.id.headerOne);

        productNameTwo = view.findViewById(R.id.productNameTwo);
        productImageTwo = view.findViewById(R.id.productImageTwo);
        closeButtonTwo = view.findViewById(R.id.closeButtonTwo);
        headerTwo = view.findViewById(R.id.headerTwo);

        comparisionList = view.findViewById(R.id.comparisionList);
        dragAndDropView = view.findViewById(R.id.dragAndDropView);

        progressBar = view.findViewById(R.id.progress);
        progressBar.setVisibility(View.GONE);
        imgNoData = view.findViewById(R.id.noDataFound);
        imgNoData.setVisibility(View.GONE);

        scrollView = view.findViewById(R.id.scrollView);
        leftArrow = view.findViewById(R.id.leftArrow);
        rightArrow = view.findViewById(R.id.rightArrow);

        productName.setText(storePreference.getStringValue(GlobalData.SELECTED_MODEL_NAME));
        productName.setSelected(true);

        img_broucher.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), HyperMEnquiryForm.class));
            }
        });

        img_rating.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), ProductFeedbackFormActivity.class));
            }
        });

        layout1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), HyperMEnquiryForm.class));
            }
        });

        if (CommonMethods.isNetworkAvailable(getActivity())) {
            getAllComparisonDetailsFromServer();
        } else {
            checkLocalComparition();
        }

        dragAndDropView.setVisibility(View.GONE);
        headerOne.setVisibility(View.INVISIBLE);
        headerTwo.setVisibility(View.INVISIBLE);

        closeButtonOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int p = (int) closeButtonOne.getTag();
                LinearLayout layout = (LinearLayout) itemLayout.getChildAt(p);
                LinearLayout v1 = (LinearLayout) layout.getChildAt(0);
                ImageView imageView = (ImageView) v1.getChildAt(0);
                TextView textView = (TextView) v1.getChildAt(1);
                v1.setBackgroundColor(Color.parseColor("#10000000"));
                imageView.setAlpha(1.0f);
                textView.setAlpha(1.0f);
                v1.setEnabled(true);

                if (comparisonTwo == null) {
                    comparisonOne = null;
                    headerOne.setVisibility(View.INVISIBLE);
                    ADAPTER.update(comparisonOne, comparisonTwo);
                } else {
                    comparisonOne = comparisonTwo;
                    comparisonTwo = null;
                    headerTwo.setVisibility(View.INVISIBLE);
                    ADAPTER.update(comparisonOne, comparisonTwo);

                    closeButtonOne.setTag(closeButtonTwo.getTag());
                    int pos = (int) closeButtonOne.getTag();

                    productNameOne.setText(MODELS.getCompareModel().get(pos).getModel().getModelName());
                    Glide.with(Objects.requireNonNull(getActivity()))
                            .load(MODELS.getCompareModel().get(pos).getModel().getModelImageUrl().trim()).into(productImageOne);
                    productNameOne.setSelected(true);
                }
            }
        });

        closeButtonTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int p = (int) closeButtonTwo.getTag();
                LinearLayout layout = (LinearLayout) itemLayout.getChildAt(p);
                LinearLayout v1 = (LinearLayout) layout.getChildAt(0);
                ImageView imageView = (ImageView) v1.getChildAt(0);
                TextView textView = (TextView) v1.getChildAt(1);
                v1.setBackgroundColor(Color.parseColor("#10000000"));
                imageView.setAlpha(1.0f);
                textView.setAlpha(1.0f);
                v1.setEnabled(true);

                comparisonTwo = null;
                headerTwo.setVisibility(View.INVISIBLE);
                ADAPTER.update(comparisonOne, comparisonTwo);
            }
        });

        dragAndDropView.setOnDragListener(new View.OnDragListener() {
            @Override
            public boolean onDrag(View v, DragEvent event) {
                try {
                    int action = event.getAction();
                    LinearLayout v1 = (LinearLayout) event.getLocalState();

                    switch (action) {
                        case DragEvent.ACTION_DRAG_STARTED:
                            dragAndDropView.setVisibility(View.VISIBLE);
                            break;
                        case DragEvent.ACTION_DROP: {
                            dragAndDropView.setVisibility(View.GONE);

                            if (comparisonOne != null && comparisonTwo != null) {
                                Toast.makeText(getActivity(), "Maximum two models to compare", Toast.LENGTH_SHORT).show();
                            } else {
                                ImageView imageView = (ImageView) v1.getChildAt(0);
                                TextView textView = (TextView) v1.getChildAt(1);
                                v1.setBackgroundColor(Color.parseColor("#40000000"));
                                imageView.setAlpha(0.3f);
                                textView.setAlpha(0.3f);
                                v1.setEnabled(false);

                                int pos = (int) v1.getTag();
                                if (comparisonOne == null) {
                                    comparisonOne = MODELS.getCompareModel().get(pos).getCategory();
                                    headerOne.setVisibility(View.VISIBLE);
                                    closeButtonOne.setTag(pos);

                                    productNameOne.setText(MODELS.getCompareModel().get(pos).getModel().getModelName());
                                    Glide.with(Objects.requireNonNull(getActivity()))
                                            .load(MODELS.getCompareModel().get(pos).getModel().getModelImageUrl().trim()).into(productImageOne);
                                    productNameOne.setSelected(true);
                                } else if (comparisonTwo == null) {
                                    comparisonTwo = MODELS.getCompareModel().get(pos).getCategory();
                                    headerTwo.setVisibility(View.VISIBLE);
                                    closeButtonTwo.setTag(pos);

                                    productNameTwo.setText(MODELS.getCompareModel().get(pos).getModel().getModelName());
                                    Glide.with(Objects.requireNonNull(getActivity()))
                                            .load(MODELS.getCompareModel().get(pos).getModel().getModelImageUrl().trim()).into(productImageTwo);
                                    productNameTwo.setSelected(true);
                                }
                                ADAPTER.update(comparisonOne, comparisonTwo);
                            }
                        }
                        break;
                        case DragEvent.ACTION_DRAG_ENDED: {
                            dragAndDropView.setVisibility(View.GONE);
                        }
                        break;
                        default:
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }
        });

        rightArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int itemwidth = itemLayout.getMeasuredWidth() / itemLayout.getChildCount();
                int width = itemLayout.getMeasuredWidth();
                int sWidth = scrollView.getMeasuredWidth();
                int xPos = scrollView.getScrollX();

                if ((sWidth + xPos) < width) {
                    scrollView.scrollTo((xPos + itemwidth), 0);
                }

            }
        });

        leftArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int itemwidth = itemLayout.getMeasuredWidth() / itemLayout.getChildCount();
                int xPos = scrollView.getScrollX();
                if (xPos > 0) {
                    scrollView.scrollTo((xPos - itemwidth), 0);
                }

            }
        });
    }

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

    @Override
    public void onDetach() {
        super.onDetach();
    }

    private void getAllComparisonDetailsFromServer() {
        progressBar.setVisibility(View.VISIBLE);
        restService.getAllComparisonDetails(storePreference.getStringValue(GlobalData.SELECTED_MODEL)).enqueue(new Callback<RootGetAllComparisonModel>() {
            @Override
            public void onResponse(Call<RootGetAllComparisonModel> call, Response<RootGetAllComparisonModel> response) {
                progressBar.setVisibility(View.GONE);

                SharedPreferences pref = Objects.requireNonNull(getActivity()).getSharedPreferences("PRODUCT_MODULE", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = pref.edit();

                if (response.body() != null && response.body().getStatus() == 200) {
                    if (response.body().getDataModel() != null &&
                            response.body().getDataModel().getComparisonCategoryList().size() > 0) {

                        MODELS = response.body().getDataModel();
                        Gson gson = new Gson();
                        JsonElement jsonElement = gson.toJsonTree(
                                MODELS, new TypeToken<ComparisonDataModel>() {
                                }.getType());
                        editor.putString("COMPARITION_" + storePreference.getStringValue(GlobalData.SELECTED_MODEL),
                                jsonElement.toString()).apply();

                        Glide.with(getActivity()).load(MODELS
                                .getComparisonModelList().getModelImageUrl().trim()).into(productImage);
                        ADAPTER = new ComparisionExpandableListAdapterNew(getActivity(), MODELS.getComparisonCategoryList(),
                                comparisonOne, comparisonTwo);
                        comparisionList.setAdapter(ADAPTER);
                        setItemLayout();
                    } else {
                        checkLocalComparition();
                    }
                } else if (response.body() != null && response.body().getStatus() == 401) {
                    GlobalData.canLogout = true;
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                    Objects.requireNonNull(getActivity()).finish();

                } else if (response.body() != null && response.body().getStatus() == 406) {
                    checkLocalComparition();
                } else if (response.errorBody() != null) {
                    Gson gson = new Gson();
                    ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                    GlobalData.showToast(Objects.requireNonNull(getActivity()), message.getMessage(), Toast.LENGTH_SHORT).show();
                    if (message.getStatus() == 401) {
                        GlobalData.canLogout = true;
                        startActivity(new Intent(getActivity(), LoginActivity.class));
                        Objects.requireNonNull(getActivity()).finish();
                    }
                    checkLocalComparition();
                } else {
                    checkLocalComparition();
                }
            }

            @Override
            public void onFailure(Call<RootGetAllComparisonModel> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                if (t.getMessage() != null) {
                    CommonMethods.showToast(getActivity(), t.getMessage()).show();
                    checkLocalComparition();
                }
            }
        });
    }

    private void checkLocalComparition() {
        SharedPreferences pref = Objects.requireNonNull(getActivity()).getSharedPreferences("PRODUCT_MODULE", Context.MODE_PRIVATE);
        if (pref.getString("COMPARITION_" + storePreference.getStringValue(GlobalData.SELECTED_MODEL), null) != null) {
            Gson gson = new Gson();
            MODELS = gson.fromJson(
                    pref.getString("COMPARITION_" + storePreference.getStringValue(GlobalData.SELECTED_MODEL), null),
                    new TypeToken<ComparisonDataModel>() {
                    }.getType());

            Glide.with(getActivity()).load(MODELS
                    .getComparisonModelList().getModelImageUrl().trim()).into(productImage);
            ADAPTER = new ComparisionExpandableListAdapterNew(getActivity(), MODELS.getComparisonCategoryList(), comparisonOne, comparisonTwo);
            comparisionList.setAdapter(ADAPTER);
            setItemLayout();
        } else {
            imgNoData.setVisibility(View.VISIBLE);
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void setItemLayout() {
        itemLayout.removeAllViews();
        if (MODELS.getCompareModel().size() > 0) {
            expandButton.setVisibility(View.VISIBLE);
            for (int i = 0; i < MODELS.getCompareModel().size(); i++) {
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.comparison_button_layout, null);
                LinearLayout linearLayout1 = view.findViewById(R.id.lineardrag);
                ImageView imageView = view.findViewById(R.id.image);
                TextView textView = view.findViewById(R.id.textButton);
                linearLayout1.setId(i);

                linearLayout1.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        LinearLayout v1 = (LinearLayout) itemLayout.getChildAt(v.getId());
                        LinearLayout layout = (LinearLayout) v1.getChildAt(0);
                        layout.setTag(v.getId());
                        dragAndDropView.setVisibility(View.VISIBLE);
                        ClipData data = ClipData.newPlainText("", "");
                        View.DragShadowBuilder shadow = new View.DragShadowBuilder(layout);
                        v.startDrag(data, shadow, layout, 0);
                        return false;
                    }

                });

                textView.setText(MODELS.getCompareModel().get(i).getModel().getModelName());
                Glide.with(Objects.requireNonNull(getActivity())).load(MODELS.getCompareModel().get(i).getModel().getModelImageUrl().trim()).into(imageView);
                itemLayout.addView(view);
            }
        } else {
            expandButton.setVisibility(View.GONE);
        }
        setLeftRightArrow();
    }

    private void setLeftRightArrow() {
        if (itemLayout.getChildCount() > 0) {
            if (itemLayout.getMeasuredWidth() > 0) {
                int width = itemLayout.getMeasuredWidth();
                boolean isScrollable = scrollView.getWidth() < width + scrollView.getPaddingStart() + scrollView.getPaddingEnd();
                if (isScrollable) {
                    leftArrow.setVisibility(View.VISIBLE);
                    rightArrow.setVisibility(View.VISIBLE);
                } else {
                    leftArrow.setVisibility(View.GONE);
                    rightArrow.setVisibility(View.GONE);
                }
            } else {
                itemLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        int width = itemLayout.getMeasuredWidth();
                        boolean isScrollable = scrollView.getWidth() < width + scrollView.getPaddingStart() + scrollView.getPaddingEnd();
                        if (isScrollable) {
                            leftArrow.setVisibility(View.VISIBLE);
                            rightArrow.setVisibility(View.VISIBLE);
                        } else {
                            leftArrow.setVisibility(View.GONE);
                            rightArrow.setVisibility(View.GONE);
                        }
                        itemLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    }
                });
            }
        } else {
            leftArrow.setVisibility(View.GONE);
            rightArrow.setVisibility(View.GONE);
        }
    }

    @Override
    public void onExpansionUpdate(float expansionFraction, int state) {
        expandButton.setRotation(expansionFraction * 0);

        if (state == ExpandableLayout.State.EXPANDED) {
            setLeftRightArrow();
        }
    }

    @Override
    public void onClick(View view) {
        expandableLayout.toggle();
        if (isOpened) {
            expandButton.setImageResource(R.drawable.leftcompare);
            isOpened = false;
        } else {
            expandButton.setImageResource(R.drawable.rightcompare);
            isOpened = true;
        }
    }
}
