package com.tomastc.ht_nki;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomastc.ht_nki.Adapter.Stock_Check_Adapter;
import com.tomastc.ht_nki.ListData.StockCheck_list_item;
import com.tomastc.ht_nki.lib.AlertProgress;
import com.tomastc.ht_nki.lib.KeyMapping;
import com.tomastc.ht_nki.lib.Scanner;
import com.tomastc.ht_nki.lib.Settings;
import com.tomastc.ht_nki.lib.common.AsyncHttpClient;
import com.tomastc.ht_nki.lib.common.Utils;

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

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class StockCheck_Activity extends Scanner implements View.OnClickListener {


    TextView txt_part_no ,txt_total;
    EditText edt_tire_week;
    Map<String, StockCheck_list_item> map_item;
    List<StockCheck_list_item> list_item;
    List<String> load_list_item;
    Dialog dialog;
    Stock_Check_Adapter stock_check_adapter;
    RecyclerView view_stock_data;
    Set<String> uniqueItemIds;

    Double sum_total=0.00;

    DecimalFormat decimalFormat;

    AlertProgress alert;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stock_check);

        map_item = new LinkedHashMap<>();
        list_item = new ArrayList<StockCheck_list_item>();
        load_list_item = new ArrayList<>();
        uniqueItemIds = new HashSet<>();

        alert = new AlertProgress(StockCheck_Activity.this);

        decimalFormat = new DecimalFormat("#,#00.00");

        txt_part_no = findViewById(R.id.txt_part_no);
        edt_tire_week = findViewById(R.id.edt_tire_week);
        txt_total = findViewById(R.id.txt_total);

        view_stock_data = findViewById(R.id.view_data_stock_check);
        view_stock_data.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        view_stock_data.setHasFixedSize(true); // ตั้งค่าให้ `RecyclerView` มีขนาดคงที่
        view_stock_data.setRecycledViewPool(new RecyclerView.RecycledViewPool());
        view_stock_data.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        view_stock_data.setItemAnimator(new DefaultItemAnimator());

        Items_Master();


        txt_part_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                search_part();
            }
        });



    }

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

        Check_Stock();

    }

    private void Items_Master() {
        map_item.clear();
        list_item.clear();
        alert.setMessage("           Loading environment....         ");
        alert.show();
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "LIST/ITEMS");


            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), "Items response: " + response);

                    try{
                        List<String> items = new ArrayList<>();
                        String check_items="";
                        JSONArray jArray = new JSONArray(response);
                        for(int i=0;i<jArray.length();i++) {

                            items.add(jArray.getJSONObject(i).getString("item_id"));

                        }
                        alert.dismiss();
                        Settings.setStock_check_item(items);
                    }catch (JSONException e) {
                        alert.dismiss();
                        new SweetAlertDialog(StockCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            alert.dismiss();
            new SweetAlertDialog(StockCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Check_Stock() {
        list_item.clear();
        sum_total = 0.0;
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "ITEM/STOCK/CHECK");
            json.put("item_id", txt_part_no.getText().toString());
            json.put("tire_week", edt_tire_week.getText().toString());

            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{
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0) {
                            new SweetAlertDialog(StockCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("Stock data not found!!")
                                    .show();
                        }else {

                            // Load response data to table view

                            for (int i = 0; i < jArray.length(); i++) {
                                list_item.add(new StockCheck_list_item(
                                        String.valueOf(i+1),
                                        jArray.getJSONObject(i).getString("item_id"),
                                        jArray.getJSONObject(i).getString("tire_week"),
                                        jArray.getJSONObject(i).getString("location_id"),
                                        jArray.getJSONObject(i).getString("lot_no"),
                                        "0",
                                        jArray.getJSONObject(i).getString("qty")));

                                if(!txt_part_no.getText().toString().trim().equals("")) {
                                    edt_tire_week.setText(jArray.getJSONObject(i).getString("tire_week"));
                                }
                                Double qty = 0.0;
                                String str_qty =  jArray.getJSONObject(i).getString("qty");
                                qty = Double.valueOf(str_qty);
                                sum_total = (sum_total + qty);
                            }

                        }
                        ViewData();

                    }catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void ViewData() {

        txt_total.setText(String.valueOf(decimalFormat.format(sum_total)));
        stock_check_adapter = new Stock_Check_Adapter(list_item, this);
        view_stock_data.setAdapter(stock_check_adapter);
    }
    private void search_part() {
        // Initialize dialog
        dialog = new Dialog(StockCheck_Activity.this);
        dialog.setContentView(R.layout.dialog_searchable_spinner);
        dialog.getWindow().setLayout(300, 300);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();

        // Initialize and assign variable
        EditText editText = dialog.findViewById(R.id.edit_text);
        ListView listView = dialog.findViewById(R.id.list_view);

//         Initialize array adapter
        ArrayAdapter<String> adapter = new ArrayAdapter<>
                (StockCheck_Activity.this, android.R.layout.simple_list_item_1, Settings.getStock_check_item());

        // set adapter
        listView.setAdapter(adapter);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                adapter.getFilter().filter(s);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String item_code = adapter.getItem(position);
                Log.d("TOT","Data item Code   :  "+ item_code );
                txt_part_no.setText(item_code);
                dialog.dismiss();


            }
        });

    }



    private void dialog_massage_not_match(){

        TextView customTextView = new TextView(StockCheck_Activity.this);
        customTextView.setText("Ticket No do not match");
        customTextView.setTextColor(Color.RED);
        customTextView.setTextSize(16);
        customTextView.setGravity(Gravity.CENTER);

        new SweetAlertDialog(StockCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                .setTitleText("WARNING")
                //.setContentText("Ticket No do not match")
                .setCustomView(customTextView)
                .setConfirmText("NG")
                .setConfirmButtonBackgroundColor(Color.RED)
                .show();


    }
    private void dialog_massage_insufficient(){
        TextView customTextView = new TextView(StockCheck_Activity.this);
        customTextView.setText("Insufficient information");
        customTextView.setTextColor(Color.RED);
        customTextView.setTextSize(16);
        customTextView.setGravity(Gravity.CENTER);

        new SweetAlertDialog(StockCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                .setTitleText("WARNING")
                //.setContentText("Ticket No do not match")
                .setCustomView(customTextView)
                .setConfirmText("NG")
                .setConfirmButtonBackgroundColor(Color.RED)
                .show();
    }
    private void dialog_massage_complete(){
        new SweetAlertDialog(StockCheck_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
//                        if (clear_data){
//                            txt_part_name.setText("");
//                            txt_part_name.setBackgroundResource(R.drawable.button_background_gray);
//                            txt_part_name.setTextColor(Color.BLACK);
//                            sDialog.dismiss();
//                        }else {
//                        txt_part_name.setText("CONFIRMED");
//                        txt_part_name.setBackgroundResource(R.drawable.button_background_green);
//                        txt_part_name.setTextColor(Color.BLACK);
                        sDialog.dismiss();
//                        }

                    }

                })
                .setTitleText("INFORMATION")
                .setContentText("Operation complete!")
                .show();

        /// Clear Data
        //event_clear();

    }
    private void event_clear() {
        txt_part_no.setText("");
        edt_tire_week.setText("");
        txt_total.setText("0.00");
        sum_total = Double.parseDouble("0");
        list_item.clear();

        ViewData();

    }
    private void event_ok(){

        String parts_no = txt_part_no.getText().toString();
        String tire_week = edt_tire_week.getText().toString();

        if (parts_no.isEmpty()){
            Log.e("ToT","=====>>>>> Data On if" );
            TextView customTextView = new TextView(StockCheck_Activity.this);
            customTextView.setText("Please Complete The Information");
            customTextView.setTextColor(Color.GRAY);
            customTextView.setTextSize(14);
            customTextView.setGravity(Gravity.CENTER);

            new SweetAlertDialog(StockCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    //.setContentText("Ticket No do not match")
                    .setCustomView(customTextView)
                    .setConfirmText("OK")
                    .setConfirmButtonBackgroundColor(Color.GREEN)
                    .show();

        }else {
            Log.e("ToT","=====>>>>> Data On else" );
            Check_Stock();
            //fitter_data_(tire_week);
        }
    }


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

            case R.id.btn_ok:
                event_ok();
                break;

            case R.id.btn_clear:
                event_clear();
                break;
        }
    }

    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {
        if(data.trim().equals(""))
            return;

        try {

            Log.d(getString(R.string.tag), "data scan: " + data);
            String[] tokens = data.split(getString(R.string.DELIMITER_SCAN_TOKEN),-1);
            Log.d(getString(R.string.tag), Arrays.deepToString(tokens));
            String resultToken = tokens[0];

            if (tokens.length == 1){

               txt_part_no.setText(data);
               Check_Stock();

            }
            else
            {
                new SweetAlertDialog(StockCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Invalid QR code!")
                        .show();
            }

            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

        } catch (Exception e) {
            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode >= KeyMapping.P1.getId()
                && keyCode <= KeyMapping.P4.getId())
        {
            switch (KeyMapping.fromId(keyCode)) {
                case P1:
                    finish();
                    break;

                case P3:
                   // Clear_layout();
                    break;

                case P4://ok
                    //ButtonClick_OK();
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }
}