package com.cygnusa.hyperm.fragments;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.InputType;
import android.util.LayoutDirection;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
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.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.ErrorResponse;
import com.cygnusa.hyperm.wrappers.GetAllSalesProcessModel;
import com.cygnusa.hyperm.wrappers.SalesProcessDataModel;
import com.cygnusa.hyperm.wrappers.SalesProcessHotspot;

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

import io.github.douglasjunior.androidSimpleTooltip.ArrowDrawable;
import io.github.douglasjunior.androidSimpleTooltip.SimpleTooltip;
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 SalesProcessFragment extends Fragment implements View.OnClickListener {
    Animation zoomOutAnimation;
    ImageView imageView;
    FrameLayout frameLayout;
    ArrayList<ImageView> views = new ArrayList<>();
    StorePreference storePreference;
    int colorClickPosition = 0;
    private ProgressBar progressBar;
    ApiService restService;
    double width = 1024.0;
    double height = 660.0;
    private Activity activity;

    List<String> processImage = null;
    public ImageView imgLogo;
    private LinearLayout linear_title;
    List<SalesProcessDataModel> MODELS = new ArrayList<>();
    private SimpleTooltip popup;
    private ImageView imgNoData;
    private LinearLayout lloutWhole;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_sales_process, null);
        initViews(view);

        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));
            }
        });
        frameLayout.getViewTreeObserver().addOnGlobalLayoutListener(listener);
        return view;
    }

    private ViewTreeObserver.OnGlobalLayoutListener listener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            double height = frameLayout.getHeight() / 100.00;
            int newWidth = (int) (height * 155.15);
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) frameLayout.getLayoutParams();
            params.width = newWidth;
            params.height = frameLayout.getHeight();
            params.gravity = Gravity.CENTER;
            params.weight = 0f;
            frameLayout.setLayoutParams(params);
            if (CommonMethods.isNetworkAvailable(activity)) {
                getAllSalesProcess();
            } else {
                checkLocalSalesProcess();
            }

            frameLayout.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
        }
    };

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

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

    private void getAllSalesProcess() {
        progressBar.setVisibility(View.VISIBLE);
        restService.getAllSalesProcessModel(storePreference.getStringValue(GlobalData.SELECTED_MODEL)).enqueue(new Callback<GetAllSalesProcessModel>() {
            @Override
            public void onResponse(Call<GetAllSalesProcessModel> call, Response<GetAllSalesProcessModel> 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) {
                    MODELS = response.body().getSalesProcessDataList();
                    if (MODELS != null && MODELS.size() > 0) {
                        Gson gson = new Gson();
                        JsonElement jsonElement = gson.toJsonTree(
                                MODELS, new TypeToken<List<SalesProcessDataModel>>() {
                                }.getType());
                        editor.putString("SALES_PROCESS_" + storePreference.getStringValue(GlobalData.SELECTED_MODEL),
                                jsonElement.toString()).apply();
                        processImage = new ArrayList<>();
                        colorClickPosition = 0;
                        setColorButtons(MODELS);
                        for (int i = 0; i < MODELS.size(); i++) {
                            processImage.add(MODELS.get(i).getSalesProcessImage().getImageUrl());
                        }
                        if (processImage != null && processImage.size() > 0) {
                            for (ImageView view : views) {
                                view.clearAnimation();
                                frameLayout.removeView(view);
                            }
                            setImageView(colorClickPosition);

                        }
                    } else {
                        checkLocalSalesProcess();

                    }
                } 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) {
                    checkLocalSalesProcess();
                } 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();
                    }
                } else {
                    checkLocalSalesProcess();
                }
            }

            @Override
            public void onFailure(Call<GetAllSalesProcessModel> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                checkLocalSalesProcess();
                if (t.getMessage() != null) {
                    Log.e("Size", t.getMessage());
                }
            }
        });


    }

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

            processImage = new ArrayList<>();
            colorClickPosition = 0;
            setColorButtons(MODELS);
            for (int i = 0; i < MODELS.size(); i++) {
                processImage.add(MODELS.get(i).getSalesProcessImage().getImageUrl());
            }

            if (processImage != null && processImage.size() > 0) {
                for (ImageView view : views) {
                    view.clearAnimation();
                    frameLayout.removeView(view);
                }
                setImageView(colorClickPosition);

            }
        } else {
            lloutWhole.setVisibility(View.GONE);
            imgNoData.setVisibility(View.VISIBLE);
        }
    }

    private void setColorButtons(final List<SalesProcessDataModel> data) {
        linear_title.removeAllViews();
        if (data != null) {
            for (int i = 0; i < data.size(); i++) {
                View view = LayoutInflater.from(activity).inflate(R.layout.personalization_button_layout, null);
                final LinearLayout linearLayout1 = view.findViewById(R.id.lineardrag);
                final TextView imageView = view.findViewById(R.id.txt_round);
                final TextView textView = view.findViewById(R.id.txt_name);
                view.setId(i);
                imageView.setId(i);
                textView.setId(i);
                if (colorClickPosition == linearLayout1.getId())
                    textView.setBackgroundDrawable(ContextCompat.getDrawable(activity, R.drawable.edt_border));
                else
                    textView.setBackgroundDrawable(ContextCompat.getDrawable(activity, R.drawable.edt_unselected_border));

                textView.setText(data.get(i).getTitle());
                linearLayout1.setId(i);
                linearLayout1.setTag(i + "");
                textView.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
                linearLayout1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        colorClickPosition = linearLayout1.getId();
                        progressBar.setVisibility(View.VISIBLE);
                        for (ImageView view : views) {
                            view.clearAnimation();
                            frameLayout.removeView(view);
                        }
                        setImageView(linearLayout1.getId());
                        setColorButtons(data);
                        progressBar.setVisibility(View.GONE);
                    }
                });
                linear_title.addView(view);
            }
        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.logo:
                activity.onBackPressed();
                break;
            default:

        }
    }

    private void initViews(View view) {

        activity = getActivity();
        linear_title = view.findViewById(R.id.linear_title);

        storePreference = new StorePreference(activity);

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

        imageView = view.findViewById(R.id.imageView);
        frameLayout = view.findViewById(R.id.hotspot_layout);
        imgLogo = view.findViewById(R.id.logo);
        imgLogo.setOnClickListener(this);
        restService = ((MainApplication) activity.getApplication()).getClient();
        TextView txtName = view.findViewById(R.id.textView);
        txtName.setText(storePreference.getStringValue(GlobalData.SELECTED_MODEL_NAME));
        imgNoData = view.findViewById(R.id.noDataFound);
        imgNoData.setVisibility(View.GONE);
        lloutWhole = view.findViewById(R.id.whole_layout);
    }

    private void setImageView(int clickPosition) {
        if (processImage != null) {
            Glide.with(activity).load(processImage.get(clickPosition)).listener(new RequestListener<Drawable>() {
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                    return false;
                }

                @Override
                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                    if (popup != null)
                        popup.dismiss();
                    setHotspot(colorClickPosition);
                    return false;

                }
            }).into(imageView);
        } else {
            Log.e("Response", "null inside");
        }
    }

    @SuppressLint("NewApi")
    public View viewPopup(int id, int clickPosition) {
        View view = LayoutInflater.from(activity).inflate(R.layout.popup_window_card, null, false);
        ImageView image = view.findViewById(R.id.popup_image);
        TextView textView1 = view.findViewById(R.id.text_title);
        TextView textViewdesc = view.findViewById(R.id.desc);
        ImageView imgplay_video = view.findViewById(R.id.play_video);
        final ImageView imgClose = view.findViewById(R.id.img_close_window);
        imgClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popup.dismiss();
            }
        });

        imgplay_video.setVisibility(View.GONE);

        final Configuration configuration = getResources().getConfiguration();
        if (configuration.getLayoutDirection() == LayoutDirection.RTL) {
            textView1.setGravity(Gravity.RIGHT);
            textViewdesc.setGravity(Gravity.RIGHT);
        } else {
            textViewdesc.setGravity(Gravity.LEFT);
            textView1.setGravity(Gravity.LEFT);
        }

        for (int posId = 0; posId < MODELS.get(clickPosition).getSalesProcessImage().getSalesProcessHotspots().size(); posId++) {
            if (id == posId) {
                List<SalesProcessHotspot> processHotspots = MODELS.get(clickPosition).getSalesProcessImage().getSalesProcessHotspots();
                Glide.with(activity).load(processHotspots.get(posId).getFileUrl()).into(image);
                textView1.setText(processHotspots.get(posId).getTitle());
                textViewdesc.setText(processHotspots.get(posId).getDescription());
            }
        }

        return view;
    }

    public void setHotspot(final int clickPosition) {
        for (ImageView view : views) {
            view.clearAnimation();
            frameLayout.removeView(view);
        }
        double w = frameLayout.getWidth() / 100.0;
        double h = frameLayout.getHeight() / 100.0;
        double mwi = getResources().getDimension(R.dimen.textSizeLarge);
        int img_w_h = (int) (frameLayout.getWidth() * (mwi / width));
        views = new ArrayList<>();

        for (int i = 0; i < MODELS.get(clickPosition).getSalesProcessImage().getSalesProcessHotspots().size(); i++) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(img_w_h, img_w_h);
            ImageView imageView = new ImageView(activity);
            imageView.setBackgroundColor(Color.TRANSPARENT);
            imageView.setImageResource(R.mipmap.bullet);
            imageView.setId(i);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (popup != null)
                        popup.dismiss();
                    popup = new SimpleTooltip.Builder(activity)
                            .arrowColor(getResources().getColor(R.color.bg_color))
                            .arrowDirection(ArrowDrawable.AUTO)
                            .anchorView(v)
                            .gravity(Gravity.END)
                            .maxWidth(R.dimen.layoutsizeExtraLarge)
                            .focusable(true)
                            .contentView(viewPopup(v.getId(), clickPosition), R.id.text_desc)
                            .dismissOnInsideTouch(false)
                            .dismissOnOutsideTouch(true)
                            .build();

                    popup.show();
                }
            });
            double x = 0, y = 0;
            try {
                if (MODELS.get(clickPosition).getSalesProcessImage().getSalesProcessHotspots().get(i).getProcessPointArr() != null) {
                    x = Double.valueOf(MODELS.get(clickPosition).getSalesProcessImage().getSalesProcessHotspots().get(i).getProcessPointArr().getX());
                    y = Double.valueOf(MODELS.get(clickPosition).getSalesProcessImage().getSalesProcessHotspots().get(i).getProcessPointArr().getY());
                }
            } catch (NumberFormatException e) {
                w = 0; // your default value
            }

            double newx = w * ((x / width) * 100.0) - (img_w_h / 2.0);
            double newy = h * ((y / height) * 100.0) - (img_w_h / 2.0);

            params.leftMargin = (int) newx;
            params.topMargin = (int) newy;
            zoomAnimate(imageView);
            frameLayout.addView(imageView, params);
            views.add(imageView);
        }
    }

    public void zoomAnimate(View v) {
        zoomOutAnimation = AnimationUtils.loadAnimation(activity, R.anim.zoom_out);
        v.startAnimation(zoomOutAnimation);
    }
}