package com.ttiglobal.inttilectgpchat.fragments;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.core.content.ContextCompat;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.ttiglobal.inttilectgpchat.ProductFeedbackFormActivity;
import com.ttiglobal.inttilectgpchat.R;
import com.ttiglobal.inttilectgpchat.SuzukiEnquiryForm;
import com.ttiglobal.inttilectgpchat.util.ApiService;
import com.ttiglobal.inttilectgpchat.util.CommonMethods;
import com.ttiglobal.inttilectgpchat.util.GlobalData;
import com.ttiglobal.inttilectgpchat.util.MainApplication;
import com.ttiglobal.inttilectgpchat.util.StorePreference;
import com.ttiglobal.inttilectgpchat.wrappers.ErrorResponse;
import com.ttiglobal.inttilectgpchat.wrappers.GetAllPersonalizationModel;
import com.ttiglobal.inttilectgpchat.wrappers.PersonalizationDataModel;

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

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

import static com.ttiglobal.inttilectgpchat.MainActivity.img_broucher;
import static com.ttiglobal.inttilectgpchat.MainActivity.img_rating;
import static com.ttiglobal.inttilectgpchat.MainActivity.layout1;

public class SuzukiPersonalizationFragment extends Fragment implements View.OnClickListener {
    LinearLayout linearLayoutColor, linearLayoutColorParent, linear_wheel;
    int lastSelectedImage = -1;
    int variantClickPosition = 0;
    int colorClickPosition = 0;

    public ImageView imagCarNew;
    private StorePreference storePreference;
    int layoutLength = 0, variantLength = 0;
    private ProgressBar progressBar;
    private ImageView imageView;
    ApiService restService;
    private TextView headerTextView;
    List<PersonalizationDataModel> MODELS;

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

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.suzuki_fragment_personalization, container, false);


        imagCarNew = rootView.findViewById(R.id.imageCar1);
        storePreference = new StorePreference(getActivity());
        imageView = rootView.findViewById(R.id.logo);
        imageView.setOnClickListener(this);

        linearLayoutColor = rootView.findViewById(R.id.linear_color);
        linear_wheel = rootView.findViewById(R.id.linear_wheel);
        progressBar = rootView.findViewById(R.id.progress);
        headerTextView = rootView.findViewById(R.id.textView);
        progressBar.setVisibility(View.GONE);
        //txtName.setText(storePreference.getStringValue(GlobalData.SELECTED_MODEL_NAME));
        restService = ((MainApplication) Objects.requireNonNull(getActivity()).getApplication()).getClient();
        lastSelectedImage = -1;

        img_broucher.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), SuzukiEnquiryForm.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(), SuzukiEnquiryForm.class));
            }
        });
        if (CommonMethods.isNetworkAvailable(getActivity())) {
            getAllPersonalizationDetails();
        } else {
            checkLocalPersonalization();
        }
        return rootView;
    }

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

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

    private void getAllPersonalizationDetails() {
        progressBar.setVisibility(View.VISIBLE);
        restService.getAllPersonalizationModel(storePreference.getStringValue(GlobalData.SELECTED_MODEL)).enqueue(new Callback<GetAllPersonalizationModel>() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onResponse(@NonNull Call<GetAllPersonalizationModel> call, @NonNull Response<GetAllPersonalizationModel> 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().getPersonalizationDataModelList();
                    if (MODELS != null && MODELS.size() > 0) {
                        Gson gson = new Gson();
                        JsonElement jsonElement = gson.toJsonTree(
                                MODELS, new TypeToken<List<PersonalizationDataModel>>() {
                                }.getType());
                        editor.putString("PERSONALIZATION_" + storePreference.getStringValue(GlobalData.SELECTED_MODEL),
                                jsonElement.toString()).apply();

                        layoutLength = MODELS.get(0).getColor().size();
                        variantLength = MODELS.size();
                        Glide.with(getActivity()).load(MODELS.get(0).getColor().get(0).getImageUrl()).into(imagCarNew);
                        if (MODELS.size() > 1)
                            setWheelView(MODELS);
                        setColorButtons(MODELS, variantClickPosition, colorClickPosition);
                    } else {
                        checkLocalPersonalization();
                    }
                } else if (response.body() != null && response.body().getStatus() == 401) {
                    GlobalData.canLogout = true;
                    Objects.requireNonNull(getActivity()).finish();
                } else if (response.body() != null && response.body().getStatus() == 406) {
                    checkLocalPersonalization();
                } 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;
                        Objects.requireNonNull(getActivity()).finish();
                    }
                    checkLocalPersonalization();
                } else {
                    checkLocalPersonalization();
                }

            }

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

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

            layoutLength = Objects.requireNonNull(MODELS).get(0).getColor().size();
            variantLength = MODELS.size();
            Glide.with(getActivity()).load(MODELS.get(0).getColor().get(0).getImageUrl()).into(imagCarNew);
            if (MODELS.size() > 1)
                setWheelView(MODELS);
            setColorButtons(MODELS, variantClickPosition, colorClickPosition);
        } else {
            Toast.makeText(getActivity(), "No data found", Toast.LENGTH_SHORT).show();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void setColorButtons(final List<PersonalizationDataModel> body, final int variantClickPosition, final int clickPosition) {
        linearLayoutColor.removeAllViews();
        if (layoutLength > 1)
            for (int i = 0; i < layoutLength; i++) {
                View view = LayoutInflater.from(getActivity()).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);
                final TextView txtWhite = view.findViewById(R.id.txt_white);
                view.setId(i);
                imageView.setId(i);
                textView.setId(i);
                textView.setVisibility(View.GONE);

                if (colorClickPosition == i)
                    txtWhite.setVisibility(View.VISIBLE);
                else
                    txtWhite.setVisibility(View.GONE);

                ColorStateList csl = new ColorStateList(new int[][]{{}}, new int[]{Color.parseColor(body.get(variantClickPosition).getColor().get(i).getColor())});

                headerTextView.setText(body.get(variantClickPosition).getColor().get(clickPosition).getColorTitle());
                imageView.setBackgroundTintList(csl);
                linearLayout1.setId(i);
                linearLayout1.setTag(i + "");
                textView.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);

                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        colorClickPosition = linearLayout1.getId();
                        setColorButtons(body, variantClickPosition, colorClickPosition);
                        headerTextView.setText(body.get(variantClickPosition).getColor().get(colorClickPosition).getColorTitle());
                        Glide.with(Objects.requireNonNull(getActivity())).load(body.get(variantClickPosition).getColor().get(colorClickPosition).getImageUrl()).into(imagCarNew);
                    }
                });


                linearLayoutColor.addView(view);
            }
    }

    private void setWheelView(final List<PersonalizationDataModel> body) {
        linear_wheel.removeAllViews();

        for (int i = 0; i < variantLength; i++) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.personalization_varient_layout, null);
            final LinearLayout linearLayout1 = view.findViewById(R.id.lineardrag);
            final TextView textView = view.findViewById(R.id.txt_name);
            view.setId(i);
            textView.setId(i);
            linearLayout1.setId(i);
            linearLayout1.setTag(i + "");
            textView.setText(body.get(i).getTitle());
            textView.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
            if (variantClickPosition == i)
                textView.setBackgroundDrawable(ContextCompat.getDrawable(Objects.requireNonNull(getActivity()), R.drawable.edt_border));
            else
                textView.setBackgroundDrawable(ContextCompat.getDrawable(Objects.requireNonNull(getActivity()), R.drawable.edt_unselected_border));
            linearLayout1.setOnClickListener(new View.OnClickListener() {
                @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void onClick(View v) {
                    layoutLength = body.get(linearLayout1.getId()).getColor().size();
                    Log.e(String.valueOf(linearLayout1.getId()) + " position : ", String.valueOf(linearLayout1.getId()));
                    variantClickPosition = linearLayout1.getId();
                    colorClickPosition = 0;
                    Glide.with(Objects.requireNonNull(getActivity())).load(body.get(variantClickPosition).getColor().get(0).getImageUrl()).into(imagCarNew);
                    setColorButtons(body, variantClickPosition, colorClickPosition);
                    setWheelView(body);
                }
            });
            linear_wheel.addView(view);
        }
    }

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

