package com.toshibabd.customermanagement.adapter;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.toshibabd.customermanagement.R;
import com.toshibabd.customermanagement.model.Customer;

import java.util.ArrayList;
import java.util.List;

public class CustomerAdapter extends RecyclerView.Adapter<CustomerAdapter.CustomerViewHolder> {

    private List<Customer> customerList;
    private final Context context;
    private final List<Integer> selectedCustomerIds = new ArrayList<>();
    private final OnCustomerActionListener actionListener;

    public interface OnCustomerActionListener {
        void onCustomerEdit(Customer customer);
        void onCustomerDelete(int id, String name);
    }

    public CustomerAdapter(Context context, OnCustomerActionListener listener) {
        this.context = context;
        this.customerList = new ArrayList<>();
        this.actionListener = listener;
    }

    @NonNull
    @Override
    public CustomerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_customer, parent, false);
        return new CustomerViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull CustomerViewHolder holder, int position) {
        Customer customer = customerList.get(position);

        // 1. Bind Primary Data
        holder.nameTextView.setText(customer.getName());

        // 🟢 Mobile Number RESTORED
        holder.mobileTextView.setText(customer.getMobileNumber());
        holder.mobileTextView.setVisibility(View.VISIBLE);

        // 🟢 Product Label RESTORED
        holder.productLabelTextView.setText("Product: " + customer.getProductLabel());
        holder.productLabelTextView.setVisibility(View.VISIBLE);

        // 🟢 Category RESTORED
        holder.categoryTextView.setText("(" + customer.getCategory() + ")");
        holder.categoryTextView.setVisibility(View.VISIBLE);

        // 2. Handle Note Display
        String note = customer.getNote();
        if (note != null && !note.trim().isEmpty()) {
            holder.noteTextView.setText("Note: " + note);
            holder.noteTextView.setVisibility(View.VISIBLE);
        } else {
            holder.noteTextView.setVisibility(View.GONE);
        }

        // 3. Handle Status Display
        if (customer.isSent()) {
            String sentDate = customer.getSentDate();
            String dateDisplay = (sentDate != null && sentDate.length() >= 10) ? sentDate.substring(0, 10) : "N/A";
            holder.statusTextView.setText("SENT (" + dateDisplay + ")");
            holder.statusTextView.setTextColor(Color.parseColor("#4CAF50")); // Green
        } else {
            holder.statusTextView.setText("PENDING");
            holder.statusTextView.setTextColor(Color.parseColor("#F44336")); // Red
        }

        // 4. Handle Checkbox State and Logic
        int customerId = customer.getId();

        holder.checkBox.setOnCheckedChangeListener(null);
        holder.checkBox.setChecked(selectedCustomerIds.contains(customerId));

        holder.checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                selectedCustomerIds.add(customerId);
            } else {
                selectedCustomerIds.remove(Integer.valueOf(customerId));
            }
        });

        // 5. Handle Edit/Delete Button Clicks
        holder.editButton.setOnClickListener(v -> actionListener.onCustomerEdit(customer));
        holder.deleteButton.setOnClickListener(v -> actionListener.onCustomerDelete(customerId, customer.getName()));
    }

    @Override
    public int getItemCount() {
        return customerList.size();
    }

    // --- Public Methods for MainActivity ---

    public void setCustomers(List<Customer> newCustomers) {
        this.customerList = newCustomers;
        notifyDataSetChanged();
    }

    public List<Customer> getCustomers() {
        return customerList;
    }

    public List<Integer> getSelectedCustomerIdsAndClear() {
        List<Integer> ids = new ArrayList<>(selectedCustomerIds);
        selectedCustomerIds.clear();
        notifyDataSetChanged();
        return ids;
    }

    public List<Integer> getSelectedCustomerIds() {
        return new ArrayList<>(selectedCustomerIds);
    }

    public void clearSelectedCustomers() {
        selectedCustomerIds.clear();
        notifyDataSetChanged();
    }

    public Customer getCustomerById(int id) {
        for (Customer customer : customerList) {
            if (customer.getId() == id) {
                return customer;
            }
        }
        return null; // Not found
    }

    // --- ViewHolder Class (Restored fields) ---

    static class CustomerViewHolder extends RecyclerView.ViewHolder {
        final TextView nameTextView;
        // 🟢 RESTORED fields
        final TextView mobileTextView;
        final TextView productLabelTextView;
        final TextView categoryTextView;

        final TextView statusTextView;
        final TextView noteTextView;
        final CheckBox checkBox;
        final ImageButton editButton;
        final ImageButton deleteButton;

        CustomerViewHolder(@NonNull View itemView) {
            super(itemView);
            nameTextView = itemView.findViewById(R.id.text_customer_name);

            // 🟢 RESTORED bindings
            mobileTextView = itemView.findViewById(R.id.text_mobile_number);
            productLabelTextView = itemView.findViewById(R.id.text_product_label);
            categoryTextView = itemView.findViewById(R.id.text_customer_category);

            noteTextView = itemView.findViewById(R.id.text_note);

            statusTextView = itemView.findViewById(R.id.text_status);
            checkBox = itemView.findViewById(R.id.checkbox_select);
            editButton = itemView.findViewById(R.id.btn_edit_customer);
            deleteButton = itemView.findViewById(R.id.btn_delete_customer);
        }
    }
}