package com.tomas.ht_ydt;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.tomas.ht_ydt.Adapter.ScheduleItem_Adapter;
import com.tomas.ht_ydt.ListData.Item_list;
import com.tomas.ht_ydt.ListData.Location_list;
import com.tomas.ht_ydt.ListData.Schedule_Item;
import com.tomas.ht_ydt.ListData.Supplier_list;
import com.tomas.ht_ydt.lib.ActionType;
import com.tomas.ht_ydt.lib.Settings;
import com.tomas.ht_ydt.lib.common.AsyncHttpClient;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class Schedule_Activity extends AppCompatActivity implements View.OnClickListener{
    LinearLayout layout_supplier;
    EditText edt_date_from, edt_date_to;
    TextView txt_header;
    Dialog dialog_search;
    RecyclerView view_schedule;
    Calendar calendar, calendar_from, calendar_to;
    SimpleDateFormat date;
    List<Schedule_Item> list_item_sch;
    Map<String, Schedule_Item> map_sch_item;
    TextView txt_supplier;
    CheckBox checkBox;
    SwipeRefreshLayout swipeContainer;
    ScheduleItem_Adapter item_adapter;
    String str_date_from, str_date_to, except_complete, action_type, str_cmd, str_display_sch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_schedule);
        layout_supplier = (LinearLayout)findViewById(R.id.layout_supplier);

        list_item_sch = new ArrayList<Schedule_Item>();
        map_sch_item = new LinkedHashMap<>();

        calendar = Calendar.getInstance();
        calendar_from = Calendar.getInstance();
        calendar_to = Calendar.getInstance();
        date = new SimpleDateFormat("yyyy-MM-dd");
        str_date_from = date.format(calendar_from.getTime());
        str_date_to = date.format(calendar_to.getTime());

        txt_header = (TextView)findViewById(R.id.txt_header);
        action_type = Settings.getActionType().toString();
        str_cmd = Settings.getCMD().toString();
        txt_header.setText(action_type);

        if (action_type.trim().equals(ActionType.Action_Type.INBOUND.toString())){
            layout_supplier.setVisibility(View.VISIBLE);

        }else {//OUTBOUND
            layout_supplier.setVisibility(View.INVISIBLE);
        }

        except_complete = "0";
        checkBox = (CheckBox) findViewById(R.id.checkBox);
        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (list_item_sch.size() == 0)
                    return;

                if (checkBox.isChecked()){
                    except_complete = "1";
                    Log.d(getString(R.string.tag), "checkBox: " + "Checked");

                }else{
                    except_complete = "0";
                    Log.d(getString(R.string.tag), "checkBox: " + "not Check");
                }
            }
        });

        txt_supplier = (TextView) findViewById(R.id.txt_supplier);
        txt_supplier.setText("All");
        txt_supplier.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                search_supplier();
            }
        });

        edt_date_from = (EditText)findViewById(R.id.edt_date_from);
        edt_date_from.setText(str_date_from);
        edt_date_from.setInputType(InputType.TYPE_NULL);
        edt_date_from.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final Calendar currentDate = Calendar.getInstance();
                new DatePickerDialog(Schedule_Activity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        str_date_from = ( year+"-"+
                                (String.format("%2s",monthOfYear + 1).replace(' ','0'))+"-"+
                                (String.format("%2s",dayOfMonth).replace(' ','0')));
                        edt_date_from.setText(str_date_from);
                    }
                }, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)).show();
            }
        });

        edt_date_to = (EditText) findViewById(R.id.edt_date_to);
        edt_date_to.setText(str_date_to);
        edt_date_to.setInputType(InputType.TYPE_NULL);
        edt_date_to.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final Calendar currentDate = Calendar.getInstance();
                new DatePickerDialog(Schedule_Activity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        str_date_to = ( year+"-"+
                                (String.format("%2s",monthOfYear + 1).replace(' ','0'))+"-"+
                                (String.format("%2s",dayOfMonth).replace(' ','0')));
                        edt_date_to.setText(str_date_to);
                    }
                }, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)).show();
            }
        });

        swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer);
        swipeContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(getString(R.string.tag), "swipeContainer click:" + "click");
            }
        });
        swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swipeContainer.setRefreshing(false);
                        Load_Schedule();
                    }
                },1000);
            }
        });

        swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);

        view_schedule = (RecyclerView) findViewById(R.id.view_schedule);
        view_schedule.setHasFixedSize(true);
        view_schedule.setRecycledViewPool(new RecyclerView.RecycledViewPool());
        view_schedule.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        view_schedule.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        view_schedule.setItemAnimator(new DefaultItemAnimator());
    }

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

    private void search_supplier() {
        // Initialize dialog
        dialog_search = new Dialog(Schedule_Activity.this);
        dialog_search.setContentView(R.layout.dialog_search);
        dialog_search.getWindow().setLayout(300, 300);
        dialog_search.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog_search.show();
        // Initialize and assign variable
        SearchView searchView = dialog_search.findViewById(R.id.search);
        ListView listView = dialog_search.findViewById(R.id.listView);

        final SearchMyAdapter adapter = new SearchMyAdapter(this, Settings.getData_supplier(), new ItemClickListener_Search() {
            @Override
            public void OnItemClicked(String supplier) {
                txt_supplier.setText(supplier);
//                if (Settings.getMap_supplier().containsKey(supplier)){
//                    Supplier_list list = Settings.getMap_supplier().get(supplier);
//                    txt_supplier.setText(list.getName());
//                }
                dialog_search.dismiss();
            }
        });
        listView.setAdapter(adapter);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                adapter.getFilter().filter(newText);
                return false;
            }
        });
    }

    private void Load_Schedule() {
        try {//check date from-to

            String Supplier = "";
            if (txt_supplier.getText().toString().trim().equals("All")){
                Supplier = "";
            }else {
                Supplier = txt_supplier.getText().toString().trim();
            }

            if (checkBox.isChecked()){
                except_complete = "1";
                Log.d(getString(R.string.tag), "checkBox: " + "Checked");

            }else{
                except_complete = "0";
                Log.d(getString(R.string.tag), "checkBox: " + "not Check");
            }

            Date date_from = date.parse(str_date_from);
            Date date_to = date.parse(str_date_to);
            Log.d(getString(R.string.tag), "check date from-to: " + str_date_from+"-"+str_date_to);

            if (date_to.before(date_from)) {
                new SweetAlertDialog(Schedule_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Selected incorrect date")
                        .show();
            }else {
                map_sch_item.clear();
                try {
                    JSONObject json = new JSONObject();
                    json.put("cmd", str_cmd);
                    json.put("action_plan_date_from", edt_date_from.getText().toString().trim());
                    json.put("action_plan_date_to", edt_date_to.getText().toString().trim());
                    json.put("supplier",Supplier);
                    json.put("action_type",action_type);
                    json.put("incharge", Settings.getLoginUser().getDepartment());
                    json.put("except_complete", except_complete);

                    new AsyncHttpClient(getApplicationContext(),
                            Settings.getMgmtList().get("web_api") + "/ht_api.php",
                            json.toString()) {
                        @Override
                        protected void onFinished(String response, int resp_code) {
                            Log.d(getString(R.string.tag), "response: " + response);

                            try{
                                JSONObject jsonObject = new JSONObject(response);
                                String value = jsonObject.getString("value");
                                JSONArray jArray = new JSONArray(value);

                                if (jArray.length() == 0){
                                    Toast.makeText(Schedule_Activity.this, "Not found schedule", Toast.LENGTH_SHORT).show();
                                }else {
                                    for(int i = 0; i < jArray.length(); i++) {
                                        JSONObject obj = jArray.getJSONObject(i);
                                        JSONObject order_date = obj.getJSONObject("order_dt");
                                        String str_order_date = order_date.getString("date");
                                        str_order_date = str_order_date.substring(0, 10);
                                        Log.d(getString(R.string.tag), "str_order_date: " + str_order_date);

                                        String supplier = jArray.getJSONObject(i).getString("supplier_id").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("supplier_id").trim();
                                        String supplier_name = "";
                                        if (!supplier.isEmpty()) {
                                             if (Settings.getMap_supplier().containsKey(supplier)){
                                                 supplier_name = Settings.getMap_supplier().get(supplier).getName();

                                             }else {
                                                 supplier_name = "";
                                             }
                                        }
                                        Log.d(getString(R.string.tag), "supplier_name: " + supplier_name);

                                        if (action_type.trim().equals(ActionType.Action_Type.OUTBOUND.toString())) {
                                            str_display_sch = "0";
                                            String fifo_lot_no = jArray.getJSONObject(i).getString("lot_no").trim().trim().equals("null") ? "" : jArray.getJSONObject(i).getString("lot_no").trim().trim();
                                            String fifo_location = jArray.getJSONObject(i).getString("location_id").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("location_id").trim();
                                            String id = jArray.getJSONObject(i).getString("id");

                                            if (map_sch_item.containsKey(id)) {
                                                Schedule_Item item = map_sch_item.get(id);
                                                String lot_no = item.getFifo_lot_no();
                                                String location = item.getFifo_location();

                                                if (!fifo_lot_no.trim().equals("") && !lot_no.contains(fifo_lot_no)) {
                                                    lot_no = lot_no + ", " + fifo_lot_no;
                                                }

                                                if (!fifo_location.trim().equals("") && !location.contains(fifo_location)) {
                                                    location = location + ", " + fifo_location;
                                                }

                                                item.setFifo_lot_no(lot_no);
                                                item.setFifo_location(location);
                                                map_sch_item.put(id, item);

                                            } else {
                                                //check stock_out_min_qty, store_pd_max_qty, total_qty
                                                Double stock_out_min_qty = jArray.getJSONObject(i).getDouble("stock_out_min_qty");
                                                String store_pd_max_qty = jArray.getJSONObject(i).getString("store_pd_max_qty");
                                                Double total_stock_qty = jArray.getJSONObject(i).getDouble("total_stock_qty");
                                                String sch_status = jArray.getJSONObject(i).getString("status");

                                                if (Settings.getMENU().trim().equals(String.valueOf(ActionType.Menu.WORK_OUTBOUND))
                                                && sch_status.toString().trim().equals("IMPORTED") ){
                                                    if (stock_out_min_qty > 0){
                                                        Log.d(getString(R.string.tag), "store_pd_max_qty = " + store_pd_max_qty);
                                                        if (store_pd_max_qty == null || store_pd_max_qty.isEmpty() || store_pd_max_qty.trim().equals("null")){
                                                            str_display_sch = "0";
                                                        }else {
                                                            Double d_store_pd_max_qty = jArray.getJSONObject(i).getDouble("store_pd_max_qty");
                                                            if (total_stock_qty < d_store_pd_max_qty){
                                                                str_display_sch = "0";
                                                            }else {
                                                                str_display_sch = "1";
                                                            }
                                                        }
                                                    }else {
                                                        str_display_sch = "0";
                                                    }
                                                }else {//WORK_OUTBOUND : COMPLETED,WORKING : DELIVERY_OUTBOUND
                                                    str_display_sch = "0";
                                                }

                                                map_sch_item.put(jArray.getJSONObject(i).getString("id"),
                                                        new Schedule_Item(
                                                                jArray.getJSONObject(i).getString("id"),
                                                                jArray.getJSONObject(i).getString("ref_id"),
                                                                jArray.getJSONObject(i).getString("order_no").trim(),
                                                                str_order_date,
                                                                supplier,
                                                                supplier_name,
                                                                jArray.getJSONObject(i).getString("parts_no").trim(),
                                                                jArray.getJSONObject(i).getString("parts_name").trim(),
                                                                jArray.getJSONObject(i).getString("qty").trim(),
                                                                jArray.getJSONObject(i).getString("action_act_qty"),
                                                                jArray.getJSONObject(i).getString("dest_location_id").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("dest_location_id").trim(),
                                                                jArray.getJSONObject(i).getString("status").trim(),
                                                                jArray.getJSONObject(i).getString("control_unit"),
                                                                jArray.getJSONObject(i).getString("src_dept_id").trim(),
                                                                jArray.getJSONObject(i).getString("dest_dept_id").trim(),
                                                                jArray.getJSONObject(i).getString("product_no").trim(),
                                                                jArray.getJSONObject(i).getString("action_det").trim(),
                                                                fifo_lot_no,
                                                                fifo_location,
                                                                jArray.getJSONObject(i).getString("crusher_ratio").trim(),
                                                                jArray.getJSONObject(i).getString("virgin_qty").trim(),
                                                                jArray.getJSONObject(i).getString("crusher_qty").trim(),
                                                                jArray.getJSONObject(i).getString("unit_qty").trim(),
                                                                jArray.getJSONObject(i).getString("ref_parts_no").trim(),
                                                                str_display_sch));
                                            }
                                        }else {
                                            String dest_location_id = jArray.getJSONObject(i).getString("dest_location_id").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("dest_location_id").trim();
                                            if (dest_location_id.trim().equals("")) {
                                                for (String key : Settings.getList_location()){
                                                    Location_list list = Settings.getMap_location().get(key);
                                                    String department_id = list.getDepartment_id();
                                                    String location = list.getId();
                                                    if (department_id.trim().equals(Settings.getLoginUser().getDepartment().toString())){
                                                        dest_location_id = location;
                                                        break;
                                                    }
                                                }
                                            }
                                            Log.d(getString(R.string.tag), "dest_location_id: " + dest_location_id);
                                            map_sch_item.put(jArray.getJSONObject(i).getString("id"),
                                                    new Schedule_Item(
                                                            jArray.getJSONObject(i).getString("id"),
                                                            jArray.getJSONObject(i).getString("ref_id"),
                                                            jArray.getJSONObject(i).getString("order_no").trim(),
                                                            str_order_date,
                                                            supplier,
                                                            supplier_name,
                                                            jArray.getJSONObject(i).getString("parts_no").trim(),
                                                            jArray.getJSONObject(i).getString("parts_name").trim(),
                                                            jArray.getJSONObject(i).getString("qty").trim(),
                                                            jArray.getJSONObject(i).getString("action_act_qty"),
                                                            dest_location_id,
                                                            jArray.getJSONObject(i).getString("status").trim(),
                                                            jArray.getJSONObject(i).getString("control_unit"),
                                                            jArray.getJSONObject(i).getString("src_dept_id").trim(),
                                                            jArray.getJSONObject(i).getString("dest_dept_id").trim(),
                                                            jArray.getJSONObject(i).getString("product_no").trim(),
                                                            jArray.getJSONObject(i).getString("action_det").trim(),
                                                            "",
                                                            "",
                                                            jArray.getJSONObject(i).getString("crusher_ratio").trim(),
                                                            jArray.getJSONObject(i).getString("virgin_qty").trim(),
                                                            jArray.getJSONObject(i).getString("crusher_qty").trim(),
                                                            jArray.getJSONObject(i).getString("unit_qty").trim(),
                                                            jArray.getJSONObject(i).getString("ref_parts_no").trim(),
                                                            "0"));
                                        }
                                    }
                                }
                                Log.d(getString(R.string.tag), "map_sch_item: " + map_sch_item.size());
                                view_data();
                            }catch (JSONException e) {
                                new SweetAlertDialog(Schedule_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("ERROR")
                                        .setContentText(e.getMessage())
                                        .show();
                            }
                        }
                    }.execute();

                }catch (JSONException e) {
                    new SweetAlertDialog(Schedule_Activity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("ERROR")
                            .setContentText(e.getMessage())
                            .show();
                }
            }
        }catch (ParseException e){
            new SweetAlertDialog(Schedule_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR : check date from-to ")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void view_data() {
        list_item_sch.clear();
        if (map_sch_item.size() > 0) {
            for (String key : map_sch_item.keySet()) {
                Schedule_Item item = map_sch_item.get(key);
                String display_sch = item.getDisplay_sch();
                if (display_sch.trim().equals("0")) {
                    list_item_sch.add(
                            new Schedule_Item(
                                    item.getId(),
                                    item.getRef_id(),
                                    item.getOrder_no(),
                                    item.getOrder_dt(),
                                    item.getSupplier(),
                                    item.getSupplier_name(),
                                    item.getPart_no(),
                                    item.getPart_name(),
                                    item.getQty(),
                                    item.getAct_qty(),
                                    item.getDest_location_id(),
                                    item.getStatus(),
                                    item.getControl_unit(),
                                    item.getSrc_dept_id(),
                                    item.getDest_dept_id(),
                                    item.getProduct_no(),
                                    item.getAction_det(),
                                    item.getFifo_lot_no(),
                                    item.getFifo_location(),
                                    item.getCrusher_ratio(),
                                    item.getVirgin_qty(),
                                    item.getCrusher_qty(),
                                    item.getUnit_qty(),
                                    item.getRef_parts_no(),
                                    item.getDisplay_sch()));
                }
            }
        }
        Log.d(getString(R.string.tag), "list_item_sch: " + list_item_sch.size());
        item_adapter = new ScheduleItem_Adapter(list_item_sch, this, action_type);
        view_schedule.setAdapter(item_adapter);
        Log.d(getString(R.string.tag), "set adapter");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imb_back:
                finish();
                break;
        }
    }
}