package com.droideve.apps.dealify.activities;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.droideve.apps.dealify.R;
import com.droideve.apps.dealify.Services.GenericNotifyEvent;
import com.droideve.apps.dealify.adapter.Order.TimeLineAdapter;
import com.droideve.apps.dealify.adapter.lists.ItemsAdapter;
import com.droideve.apps.dealify.appconfig.Constances;
import com.droideve.apps.dealify.classes.Currency;
import com.droideve.apps.dealify.classes.Item;
import com.droideve.apps.dealify.classes.Order;
import com.droideve.apps.dealify.classes.OrderDelivery;
import com.droideve.apps.dealify.classes.Store;
import com.droideve.apps.dealify.classes.User;
import com.droideve.apps.dealify.controllers.SettingsController;
import com.droideve.apps.dealify.controllers.orders.OrdersController;
import com.droideve.apps.dealify.controllers.sessions.SessionsController;
import com.droideve.apps.dealify.helper.CommunFunctions;
import com.droideve.apps.dealify.restApi.OrderApis;
import com.droideve.apps.dealify.utils.DateUtils;
import com.droideve.apps.dealify.utils.ProductUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.view.Gravity.END;

public class OrderDetailActivity extends GlobalActivity implements OrderApis.OrderRestAPisDelegate {

    Toolbar toolbar;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_description)
    TextView toolbarDescription;

    @BindView(R.id.locate_btn_owner)
    AppCompatButton locate_btn_owner;
    @BindView(R.id.locate_btn_client)
    AppCompatButton locate_btn_client;

    @BindView(R.id.btn_update_status)
    AppCompatButton btn_update_status;

    @BindView(R.id.contact_btn_owner)
    AppCompatButton contact_btn_owner;

    @BindView(R.id.contact_btn_client)
    AppCompatButton contact_btn_client;

    @BindView(R.id.order_id)
    TextView order_id;
    @BindView(R.id.payment_method)
    TextView payment_method;
    @BindView(R.id.delivery_on)
    TextView delivery_on;

    @BindView(R.id.total_price)
    TextView total_price;

    @BindView(R.id.store_name)
    TextView store_name;
    @BindView(R.id.owner_address)
    TextView owner_address;

    @BindView(R.id.customer_name)
    TextView customer_name;
    @BindView(R.id.customer_address)
    TextView customer_address;

    @BindView(R.id.order_status)
    TextView order_status;


    @BindView(R.id.delivery_layout)
    LinearLayout delivery_layout;

    @BindView(R.id.delivery_label)
    TextView delivery_label;

    @BindView(R.id.delivery_value)
    TextView delivery_value;


    @BindView(R.id.item_detail)
    LinearLayout item_wrapper;

    @BindView(R.id.order_tracking)
    LinearLayout order_tracking;


    @BindView(R.id.item_wrapper_fees)
    LinearLayout item_wrapper_fees;


    private RecyclerView list;
    private Order mOrder;
    private OrderApis call;
    private Currency defaultCurrency = null;

    private String client_address, client_latitude, client_longitude, client_phone;
    private float extraFees;


    @OnClick(R.id.btn_update_status)
    void updateStatusClick(View view) {
        // display a popup

        ArrayAdapter<OrderDelivery> itemsAdapter = new ArrayAdapter<OrderDelivery>(this, android.R.layout.select_dialog_singlechoice);

        if (mOrder.getDelivery_status() == Constances.DELIVERY_STATUS.PENDING) {
            itemsAdapter.add(new OrderDelivery(getString(R.string.picked_up), Constances.DELIVERY_STATUS.ONGOING));
            itemsAdapter.add(new OrderDelivery(getString(R.string.picked_up), Constances.DELIVERY_STATUS.PICKED_UP));
            itemsAdapter.add(new OrderDelivery(getString(R.string.delivred), Constances.DELIVERY_STATUS.DELIVERED));
            itemsAdapter.add(new OrderDelivery(getString(R.string.report), Constances.DELIVERY_STATUS.REPORTED));
        } else if (mOrder.getDelivery_status() == Constances.DELIVERY_STATUS.ONGOING) {
            itemsAdapter.add(new OrderDelivery(getString(R.string.picked_up), Constances.DELIVERY_STATUS.PICKED_UP));
            itemsAdapter.add(new OrderDelivery(getString(R.string.delivred), Constances.DELIVERY_STATUS.DELIVERED));
            itemsAdapter.add(new OrderDelivery(getString(R.string.report), Constances.DELIVERY_STATUS.REPORTED));

        } else if (mOrder.getDelivery_status() == Constances.DELIVERY_STATUS.PICKED_UP) {
            itemsAdapter.add(new OrderDelivery(getString(R.string.delivred), Constances.DELIVERY_STATUS.DELIVERED));
            itemsAdapter.add(new OrderDelivery(getString(R.string.report), Constances.DELIVERY_STATUS.REPORTED));
        }

        //String[] list_status = new String[]{getString(R.string.picked_up), getString(R.string.delivred), getString(R.string.report)};

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.update_order_status);
        builder.setSingleChoiceItems(itemsAdapter, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {


            }
        });
        builder.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                int selectedPosition = ((AlertDialog) dialogInterface).getListView().getCheckedItemPosition();

                if (itemsAdapter.getItem(selectedPosition).deliver_id == Constances.DELIVERY_STATUS.REPORTED) {
                    Intent intent = new Intent(OrderDetailActivity.this, ReportOrderActivity.class);
                    intent.putExtra("order_id", mOrder.getId());
                    startActivity(intent);
                    finish();
                } else {
                    HashMap<String, String> listParams = new HashMap<>();
                    listParams.put("delivery_id", String.valueOf(SessionsController.getSession().getUser().getId()));
                    listParams.put("order_id", String.valueOf(mOrder.getId()));
                    listParams.put("status", String.valueOf(itemsAdapter.getItem(selectedPosition).deliver_id));

                    //call api to update status
                    call.updateOrderStatus(listParams);
                }
            }
        });
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }

        });

        builder.show();

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_order_detail);
        ButterKnife.bind(this);

        initToolbar();

        //delegate a listener to retrieve data
        call = OrderApis.newInstance();
        call.delegate = this;

        retrieveDatafromOrder();


        setupTimeLineRV();

    }


    @Override
    protected void onStart() {
        super.onStart();
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (android.R.id.home == item.getItemId()) {
            finish();
        }

        return super.onOptionsItemSelected(item);
    }

    private void retrieveDatafromOrder() {
        try {
            if (getIntent() != null && getIntent().hasExtra("id"))
                mOrder = OrdersController.findOrderById(getIntent().getExtras().getInt("id"));

            if (mOrder != null) {

                //get default currency from the first item
                if (mOrder.getItems() != null && mOrder.getItems().size() > 0)
                    defaultCurrency = mOrder.getItems().get(0).getCurrency();


                if (mOrder.getPayment_status() != null) {
                    String[] payment_array = mOrder.getPayment_status().split(";");
                    if (payment_array.length > 0)
                        payment_method.setText(payment_array[0]);

                    String inputDate = DateUtils.prepareOutputDate(mOrder.getCreated_at(), "dd MMMM yyyy  hh:mm", this);
                    order_id.setText("#" + mOrder.getId());
                    delivery_on.setText(inputDate);
                }

                //get user data from cf
                if (parseCustomerDataFromOrderCF(mOrder))
                    customer_address.setText(client_address);


                //set status with color
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                    CommunFunctions.getDelivetStatuFromID(order_status, mOrder.getDelivery_status());

                //hide or show update action
                btn_update_status.setVisibility(
                        (mOrder.getStatus_id() == Constances.ORDER_STATUS.DELIVERED) ||
                                (mOrder.getStatus_id() == Constances.ORDER_STATUS.REPORTED) ||
                                mOrder.getDelivery_id() == 0
                                ? View.GONE : View.VISIBLE);


                //parse products from order
                generateViewFromData(mOrder, defaultCurrency);

                //display delivery fees and commission
                setupDeliveryFee();
                
                //call apis to retrieve store and customer detail from ids
                HashMap paramsStoreAPI = new HashMap<>();
                paramsStoreAPI.put("store_id", String.valueOf(mOrder.getId_store()));
                call.getStoreDetail(paramsStoreAPI);

                HashMap paramsCustomerAPI = new HashMap<>();
                paramsCustomerAPI.put("uid", String.valueOf(mOrder.getUser_id()));
                call.getUserDetail(paramsCustomerAPI);

            }

        } catch (Exception e) {

        }
    }

    private void setupDeliveryFee() {

        //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

        )) {

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

            delivery_value.setText(
                    ProductUtils.parseCurrencyFormat(
                            Float.parseFloat(decimalFormat.format(mOrder.getDelivery_commission()))
                            , defaultCurrency));

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

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

            delivery_value.setText(
                    ProductUtils.parseCurrencyFormat(
                            Float.parseFloat(decimalFormat.format(mOrder.getDelivery_commission()))
                            , defaultCurrency));

            delivery_label.setText(this.getString(R.string.you_got));

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

    public void initToolbar() {

        toolbar = findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
        getSupportActionBar().setDisplayUseLogoEnabled(false);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        toolbarDescription.setVisibility(View.GONE);
        toolbarTitle.setText(R.string.order_detail);
    }


    private void setupTimeLineRV() {

        TimeLineAdapter adapter = new TimeLineAdapter(this, mOrder.getTimeLines());
        list = findViewById(R.id.recyclerView);
        list.setHasFixedSize(false);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        list.setLayoutManager(mLayoutManager);
        list.setAdapter(adapter);

    }


    private void generateViewFromData(final Order mOrder, final Currency _defCurrency) {

        float totalPrice = 0;
        //global fields
        LinearLayout.LayoutParams lp_match_wrap = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);


        if (mOrder != null && mOrder.getItems() != null && mOrder.getItems().size() > 0) {
            for (Item item : mOrder.getItems()) {


                LinearLayout item_detail = new LinearLayout(this);
                item_detail.setOrientation(LinearLayout.VERTICAL);
                item_detail.setLayoutParams(lp_match_wrap);

                LinearLayout linearLayout_11 = new LinearLayout(this);
                linearLayout_11.setOrientation(LinearLayout.HORIZONTAL);
                LinearLayout.LayoutParams lp_match_wrap_11 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                //lp_match_wrap_11.setMargins((int) getResources().getDimension(R.dimen.spacing_middle), 0, 0, (int) getResources().getDimension(R.dimen.spacing_middle));
                linearLayout_11.setLayoutParams(lp_match_wrap_11);

                TextView item_name = new TextView(this);
                LinearLayout.LayoutParams lp_item_name = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                lp_item_name.weight = 1;
                item_name.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_START);
                item_name.setLayoutParams(lp_item_name);
                linearLayout_11.addView(item_name);

                TextView item_price = new TextView(this);
                item_price.setGravity(END);
                item_price.setTypeface(item_price.getTypeface(), Typeface.BOLD);
                item_price.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_END);

                LinearLayout.LayoutParams lp_item_price = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                item_price.setLayoutParams(lp_item_price);
                linearLayout_11.addView(item_price);
                item_detail.addView(linearLayout_11);


                item_wrapper.addView(item_detail);


                //dynamic content
                item_name.setText(item.getName() + " x " + item.getQty());

                if (item.getAmount() > 0) {
                    //calculate  the amount based on qty
                    //double amountOrder = item.getAmount() * (item.getQty() > 0 ? item.getQty() : 1);
                    item_price.setText(ProductUtils.parseCurrencyFormat(
                            (float) item.getAmount() * item.getQty(), _defCurrency));
                    item_price.setVisibility(View.VISIBLE);

                    totalPrice += (float) item.getAmount() * item.getQty();

                } else {
                    item_price.setVisibility(View.GONE);
                }


            }

        }




        //display total price
        if (mOrder.getAmount() > 0) {
            //format 2 digit
            float amount = mOrder.getAmount();
            DecimalFormat decimalFormat = new DecimalFormat("#.##");
            amount = Float.parseFloat(decimalFormat.format(amount));

            total_price.setText(
                    ProductUtils.parseCurrencyFormat(  amount , defaultCurrency));

        } else if (totalPrice > 0) {

            DecimalFormat decimalFormat = new DecimalFormat("#.##");
            totalPrice = Float.parseFloat(decimalFormat.format(totalPrice));

            total_price.setText(
                    ProductUtils.parseCurrencyFormat(  totalPrice , defaultCurrency));

            total_price.setVisibility(View.VISIBLE);
        } else {
            total_price.setVisibility(View.GONE);
        }


    }


    @Override
    public void onStoreSuccess(Store storeData) {

        store_name.setText(storeData.getName());
        owner_address.setText(storeData.getAddress());

        //button click listener
        contact_btn_owner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String phoneNumber = storeData.getPhone();
                Intent intent = new Intent(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:" + phoneNumber.trim()));
                if (ActivityCompat.checkSelfPermission(OrderDetailActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    String[] permission = new String[]{Manifest.permission.CALL_PHONE};
                    SettingsController.requestPermissionM(OrderDetailActivity.this, permission);
                    return;
                }
                startActivity(intent);

            }
        });

        locate_btn_owner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(OrderDetailActivity.this, FindMyPlaceActivity.class);
                HashMap<String, String> params = new HashMap<>();
                params.put("discussion_id", String.valueOf(storeData.getUser_id()));
                params.put("phone_number", String.valueOf(storeData.getPhone()));
                params.put("receiver", String.valueOf(storeData.getName()));
                params.put("address", String.valueOf(storeData.getAddress()));
                params.put("latitude", String.valueOf(storeData.getLatitude()));
                params.put("longitude", String.valueOf(storeData.getLongitude()));
                intent.putExtra("params", params);
                startActivity(intent);

            }
        });

    }

    @Override
    public void onCustomerSuccess(User userData) {

        if (userData == null) {
            Toast.makeText(getApplicationContext(), getString(R.string.cant_get_user_data), Toast.LENGTH_LONG).show();
            return;
        }


        customer_name.setText(userData.getName());
        customer_address.setText(client_address);
        contact_btn_client.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //prioritize the second phone number if exist
                String phoneNumber = client_phone;
                if (phoneNumber != null) {
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    intent.setData(Uri.parse("tel:" + phoneNumber.trim()));
                    if (ActivityCompat.checkSelfPermission(OrderDetailActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                        String[] permission = new String[]{Manifest.permission.CALL_PHONE};
                        SettingsController.requestPermissionM(OrderDetailActivity.this, permission);
                        return;
                    }
                    startActivity(intent);
                }


            }
        });

        locate_btn_client.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(OrderDetailActivity.this, FindMyPlaceActivity.class);
                HashMap<String, String> params = new HashMap<>();
                params.put("discussion_id", String.valueOf(userData.getId()));
                params.put("phone_number", String.valueOf(userData.getPhone()));
                params.put("receiver", userData.getName());
                params.put("address", client_address);
                params.put("latitude", String.valueOf(client_latitude));
                params.put("longitude", String.valueOf(client_longitude));

                intent.putExtra("params", params);

                startActivity(intent);


            }
        });
    }


    private boolean parseCustomerDataFromOrderCF(Order _order) {
        if (_order != null && _order.getReq_cf_data() != null) {
            try {
                JSONObject jsonObject = new JSONObject(_order.getReq_cf_data());

                //retrieve phone number
                if (jsonObject.has("Phone"))
                    client_phone = jsonObject.getString("Phone");


                //retrieve address detail
                String addressObj = jsonObject.getString("Delivery to");
                if (addressObj != null && !addressObj.isEmpty()) {
                    String[] req_cf_data_array = addressObj.split(";");
                    if (req_cf_data_array.length >= 2) {

                        client_address = req_cf_data_array[0];
                        client_latitude = req_cf_data_array[1];
                        client_longitude = req_cf_data_array[2];

                        return true;
                    } else {
                        Toast.makeText(getApplicationContext(), getString(R.string.cant_locate_address), Toast.LENGTH_LONG).show();
                        return false;
                    }

                }


            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), getString(R.string.cant_locate_address), Toast.LENGTH_LONG).show();
                return false;
            }


        }
        return false;

    }

    @Override
    public void onOrderUpdate(JSONObject jsonObject) {

        if (jsonObject != null) {
            try {

                if (jsonObject.has("success") && jsonObject.getInt("success") == 1) {
                    Toast.makeText(getApplicationContext(), getString(R.string.order_successfuly_updated), Toast.LENGTH_LONG).show();
                    //push an eventbus to update the ui
                    EventBus.getDefault().postSticky(new GenericNotifyEvent("order_updated"));
                } else
                    Toast.makeText(getApplicationContext(), getString(R.string.error_try_later), Toast.LENGTH_LONG).show();

            } catch (JSONException e) {
                Toast.makeText(getApplicationContext(), getString(R.string.error_try_later), Toast.LENGTH_LONG).show();
            }

        }


    }

    @Override
    public void onError(OrderApis object, Map<String, String> errors) {

    }
}
