package com.droideve.apps.dealify.adapter.Order;

import android.content.Context;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatButton;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.droideve.apps.dealify.R;
import com.droideve.apps.dealify.adapter.lists.ItemsAdapter;
import com.droideve.apps.dealify.animation.ViewAnimation;
import com.droideve.apps.dealify.appconfig.Constances;
import com.droideve.apps.dealify.classes.Order;
import com.droideve.apps.dealify.helper.CommunFunctions;
import com.droideve.apps.dealify.utils.ProductUtils;
import com.droideve.apps.dealify.utils.Utils;

import org.json.JSONException;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class OrdersListExpandAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<Order> data = new ArrayList<>();

    private final Context ctx;
    private OnItemClickListener mOnItemClickListener;
    private final boolean expanded;

    public OrdersListExpandAdapter(Context context, List<Order> data, boolean expanded) {
        this.data = data;
        ctx = context;
        this.expanded = expanded;
    }

    public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
        this.mOnItemClickListener = mItemClickListener;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder vh;
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_order_expand, parent, false);
        vh = new OriginalViewHolder(v);
        return vh;
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {


        if (holder instanceof OriginalViewHolder) {
            final OriginalViewHolder view = (OriginalViewHolder) holder;

            final Order mOrder = data.get(position);

            float extraFees = 0;


            view.orderID.setText(
                    String.format(ctx.getString(R.string.statusID), mOrder.getId())
            );


            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                CommunFunctions.getDelivetStatuFromID(view.status, mOrder.getDelivery_status());


            //hide payment status for delivery
            view.order_payment_status.setVisibility(View.GONE);


            //setup product items in recyclerview
            RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(ctx, 1);
            ItemsAdapter mProductAdapter = new ItemsAdapter(ctx, mOrder.getItems());
            view.list_items.setHasFixedSize(true);
            view.list_items.setLayoutManager(mLayoutManager);
            view.list_items.setItemAnimator(new DefaultItemAnimator());
            view.list_items.setAdapter(mProductAdapter);


            //display total price
            if (mOrder.getAmount() > 0) {

                float amount = mOrder.getAmount();
                //format 2 digit

                try {
                    DecimalFormat decimalFormat = new DecimalFormat("#.##");
                     amount = Float.parseFloat(decimalFormat.format(amount));
                    view.total_price_value.setText(
                            ProductUtils.parseCurrencyFormat(  amount , mProductAdapter.getCurrency()));
                }catch (Exception e){
                     view.total_price_value.setText(
                            ProductUtils.parseCurrencyFormat(  amount , mProductAdapter.getCurrency()));
                }

                view.total_price_layout.setVisibility(View.VISIBLE);

            } else if (mProductAdapter.getTotalPrice() > 0) {

                //format 2 digit
                float totalPrice = mProductAdapter.getTotalPrice();
                try {
                    DecimalFormat decimalFormat = new DecimalFormat("#.##");
                    totalPrice = Float.parseFloat(decimalFormat.format(totalPrice));
                    view.total_price_value.setText(
                            ProductUtils.parseCurrencyFormat(  totalPrice , mProductAdapter.getCurrency()));
                }catch (Exception e){
                    view.total_price_value.setText(
                            ProductUtils.parseCurrencyFormat(  totalPrice , mProductAdapter.getCurrency()));
                }

                view.total_price_layout.setVisibility(View.VISIBLE);
            } else {
                view.total_price_layout.setVisibility(View.GONE);
            }

            //display tax if exist
            if (mOrder.getDelivery_commission()>0 && (

                    mOrder.getDelivery_status() == Constances.DELIVERY_STATUS.PENDING
                            ||
                    mOrder.getDelivery_status() == Constances.DELIVERY_STATUS.ONGOING
                            ||
                    mOrder.getDelivery_status() == Constances.DELIVERY_STATUS.PICKED_UP

            )) {

                view.delivery_layout.setVisibility(View.VISIBLE);
                DecimalFormat decimalFormat = new DecimalFormat("#.##");

                view.delivery_value.setText(
                        ProductUtils.parseCurrencyFormat(
                                Float.parseFloat(decimalFormat.format(mOrder.getDelivery_commission()))
                                , mProductAdapter.getCurrency()));

            }else if (mOrder.getDelivery_commission()>0 && mOrder.getDelivery_status() == Constances.DELIVERY_STATUS.DELIVERED) {

                view.delivery_layout.setVisibility(View.VISIBLE);
                float taxes = mOrder.getAmount() - mProductAdapter.getTotalPrice() - extraFees;
                if (taxes <= 0) view.delivery_layout.setVisibility(View.GONE);
                view.delivery_value.setText(
                        ProductUtils.parseCurrencyFormat(0, mProductAdapter.getCurrency()));

                view.delivery_label.setText(ctx.getString(R.string.you_got));

            } else {
                view.delivery_layout.setVisibility(View.GONE);
            }

            view.bt_expand.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean show = toggleLayoutExpand(!mOrder.expanded, v, view.lyt_expand);
                    data.get(position).expanded = show;
                }
            });

            view.itemOrderlayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean show = toggleLayoutExpand(!mOrder.expanded, view.bt_expand, view.lyt_expand);
                    data.get(position).expanded = show;
                }
            });

            // void recycling view
            if (mOrder.expanded = expanded) {
                view.lyt_expand.setVisibility(View.VISIBLE);
            } else {
                view.lyt_expand.setVisibility(View.GONE);
            }
            Utils.toggleArrow(mOrder.expanded, view.bt_expand, false);

            //action button
            if (mOrder.getDelivery_status() == Constances.DELIVERY_STATUS.PENDING) {
                view.btn_order_status.setVisibility(View.VISIBLE);
            } else {
                view.btn_order_status.setVisibility(View.GONE);
            }



        }
    }


    public Order getItem(int position) {

        try {
            return data.get(position);
        } catch (Exception e) {
            return null;
        }

    }

    public void addItem(Order item) {

        int index = (data.size());
        data.add(item);
        notifyItemInserted(index);

    }

    public void addAllItems(List<Order> listCats) {

        data.addAll(listCats);
        notifyDataSetChanged();

    }

    public void removeAll() {
        int size = this.data.size();

        if (size > 0) {
            for (int i = 0; i < size; i++) {
                this.data.remove(0);
            }

            if (size > 0)
                this.notifyItemRangeRemoved(0, size);

        }


    }

    private boolean toggleLayoutExpand(boolean show, View view, View lyt_expand) {
        Utils.toggleArrow(show, view);
        if (show) {
            ViewAnimation.expand(lyt_expand);
        } else {
            ViewAnimation.collapse(lyt_expand);
        }
        return show;
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public interface OnItemClickListener {
        void onOrderDetailClick(int position);

        void onContactClick(int position);

        void onUpdateStatusClick(int position);
    }

    public class OriginalViewHolder extends RecyclerView.ViewHolder {
        View itemOrderlayout;
        TextView orderID;
        TextView status;
        TextView order_payment_status;
        ImageButton bt_expand;
        View lyt_expand;
        View lyt_parent;
        RecyclerView list_items;


        LinearLayout total_price_layout;
        TextView total_price_value;


        LinearLayout btns_action;
        AppCompatButton btn_order_status;
        AppCompatButton btn_order_detail;
        AppCompatButton btn_order_contact;


        LinearLayout delivery_layout;
        TextView delivery_value;
        TextView delivery_label;


        public OriginalViewHolder(View v) {
            super(v);
            itemOrderlayout = v.findViewById(R.id.itemOrderlayout);
            orderID = v.findViewById(R.id.order_id);
            status = v.findViewById(R.id.order_status);
            order_payment_status = v.findViewById(R.id.order_payment_status);
            bt_expand = v.findViewById(R.id.bt_expand);
            lyt_expand = v.findViewById(R.id.lyt_expand);
            lyt_parent = v.findViewById(R.id.lyt_parent);
            list_items = v.findViewById(R.id.list_items);
            total_price_value = v.findViewById(R.id.total_price_value);
            total_price_layout = v.findViewById(R.id.total_price_layout);
            btns_action = v.findViewById(R.id.btns_action);
            btn_order_status = v.findViewById(R.id.btn_order_status);
            btn_order_contact = v.findViewById(R.id.btn_order_contact);
            btn_order_detail = v.findViewById(R.id.btn_order_detail);

            delivery_layout = v.findViewById(R.id.delivery_layout);
            delivery_value = v.findViewById(R.id.delivery_value);
            delivery_label = v.findViewById(R.id.delivery_label);


            //click listener
            btn_order_status.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onUpdateStatusClick(getAdapterPosition());
                    }
                }
            });
            btn_order_contact.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onContactClick(getAdapterPosition());
                    }
                }
            });
            btn_order_detail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onOrderDetailClick(getAdapterPosition());
                    }
                }
            });


        }
    }


}