package com.utopiaindustries.qualitychecker.ui.adapter;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.RecyclerView;

import com.utopiaindustries.qualitychecker.R;
import com.utopiaindustries.qualitychecker.models.InspectionCheckPoint;
import com.utopiaindustries.qualitychecker.models.InspectionDefect;
import com.utopiaindustries.qualitychecker.models.InspectionItemCheckPoint;

import java.util.List;
import java.util.stream.Collectors;

public class DefectsAdapter extends RecyclerView.Adapter<DefectsAdapter.DefectViewHolder> {

    private InspectionItemCheckPoint checkPoint;
    private List<String> defectTypes;
    private List<InspectionDefect> defects;

    private InspectionCheckPoint cp ;

    public DefectsAdapter(InspectionItemCheckPoint checkPoint,
                          List<String> defectTypes,
                          List<InspectionDefect> defects, InspectionCheckPoint cp) {
        this.checkPoint = checkPoint;
        this.defectTypes = defectTypes;
        this.defects = defects;
        this.cp = cp;

    }

    @NonNull
    @Override
    public DefectViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from( parent.getContext() )
                .inflate(R.layout.defect_item, parent, false);
        return new DefectViewHolder(view);
    }


    private void populateDefectSeveritySpinner( DefectViewHolder holder ){
        String defectType = checkPoint.getDefectSeverites().get( holder.getAdapterPosition() );
        ArrayAdapter<String> defectTypeSpinnerAdapter = new ArrayAdapter<>( holder.defectTypeSpinner.getContext(),
                android.R.layout.simple_spinner_item, defectTypes );
        defectTypeSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        holder.defectTypeSpinner.setAdapter(defectTypeSpinnerAdapter);

        String defaultSelectedDefectType = defectType;
        int defaultSelectedDefectTypePosition = defectTypes.indexOf(defaultSelectedDefectType);
        holder.defectTypeSpinner.setSelection(defaultSelectedDefectTypePosition);
    }

    private void populateDefectOptionsSpinner( DefectViewHolder holder ){
        String defect = checkPoint.getDefectTitles().get( holder.getAdapterPosition() );

        List<InspectionDefect> filteredDefects = defects.stream()
                .filter(d -> d.getCategory().equalsIgnoreCase(cp.getCategory()))
                .collect(Collectors.toList());
        List<String> defectList = filteredDefects.stream().map(InspectionDefect::getDefect).collect(Collectors.toList());


        ArrayAdapter<String> defectSpinnerAdapter = new ArrayAdapter<>( holder.defectSpinner.getContext(),
                android.R.layout.simple_spinner_item, defectList );
//        defectSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        holder.defectSpinner.setAdapter(defectSpinnerAdapter);
        // Make the dropdown appear when clicking the AutoCompleteTextView
        holder.defectSpinner.setOnClickListener(view ->  holder.defectSpinner.showDropDown());

        String defaultSelectedDefect = defect;
        int defaultSelectedDefectPosition = defectList.indexOf(defaultSelectedDefect);
        holder.defectSpinner.setText(defaultSelectedDefect);
    }

    private void populateQuantity( DefectViewHolder holder ){

        Float quantity = checkPoint.getQuantities().get( holder.getAdapterPosition() );
        if( quantity != null ){
            holder.quantity.setText( String.valueOf( quantity ) );
        } else {
            holder.quantity.setText( String.valueOf( 0f ) );
        }
    }

    @Override
    public void onBindViewHolder(@NonNull DefectViewHolder holder, int position) {

        populateDefectSeveritySpinner( holder );
        populateDefectOptionsSpinner( holder );
        populateQuantity( holder );
        // Populate defect type Spinner dropdown
        {
            holder.defectTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    String selectedItem = parent.getItemAtPosition(position).toString();
                    checkPoint.getDefectSeverites().set( holder.getAdapterPosition(), selectedItem) ;
                }
                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                }
            });

            holder.defectSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String selectedItem = parent.getItemAtPosition(position).toString();
                   checkPoint.getDefectTitles().set( holder.getAdapterPosition(), selectedItem) ;
                }
            });
//            holder.defectSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//                @Override
//                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                    String selectedItem = parent.getItemAtPosition(position).toString();
//                    checkPoint.getDefectTitles().set( holder.getAdapterPosition(), selectedItem) ;
//                }
//                @Override
//                public void onNothingSelected(AdapterView<?> parent) {
//
//                }
//            });

            holder.setUpQuantityListener( checkPoint, position );

            holder.deleteBtn.setOnClickListener(v-> {
                System.out.println( holder.getAdapterPosition() );
                removeItem( holder.getAdapterPosition() );
            });
        }
    }
    public void removeItem(int position) {
        if( position >= 0 && position <  checkPoint.getDefectSeverites().size() ){
            checkPoint.getDefectSeverites().remove( position ) ;
            checkPoint.getDefectTitles().remove( position ) ;
            checkPoint.getQuantities().remove( position );
            notifyItemRemoved( position );

        }
    }


    @Override
    public int getItemCount() {
       return Math.max( checkPoint.getDefectTitles().size(), checkPoint.getDefectTitles().size() );
    }

    public static class DefectViewHolder extends RecyclerView.ViewHolder{

        private AutoCompleteTextView defectSpinner;
        private Spinner defectTypeSpinner;
        private ImageButton deleteBtn;
        private EditText quantity;

        private TextWatcher quantityTextWatcher;

        public DefectViewHolder(@NonNull View itemView) {
            super(itemView);
            defectSpinner = itemView.findViewById( R.id.defect_spinner );
            defectTypeSpinner = itemView.findViewById( R.id.defect_type_spinner );
            deleteBtn = itemView.findViewById( R.id.delete_defect );
            quantity = itemView.findViewById( R.id.defect_quantity );
        }

        public void setUpQuantityListener( InspectionItemCheckPoint checkPoint, int position ){
            if ( quantityTextWatcher != null) {
                quantity.removeTextChangedListener( quantityTextWatcher );
            }
             quantityTextWatcher = 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) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    if( s == null || s.toString().isEmpty() ){
                        checkPoint.getQuantities().set( position , 0F );

                    } else {
                        checkPoint.getQuantities().set( position , Float.parseFloat( s.toString() ));

                    }
                }
            };

            quantity.addTextChangedListener( quantityTextWatcher );
        }

    }
}
