package com.swiftcleaner.chovey.view.adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.swiftcleaner.chovey.R;
import com.swiftcleaner.chovey.model.bean.SimilarBean;
import com.swiftcleaner.chovey.model.tool.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：马海钊
 * 时间：2024/12/25 14:00
 * 功能：
 */
public class SimilarPhotosAdapter extends RecyclerView.Adapter<SimilarPhotosAdapter.ViewHolder> {
    private final Context context;
    private List<SimilarBean> list;

    public SimilarPhotosAdapter(Context context, List<SimilarBean> list) {
        this.context = context;
        this.list = new ArrayList<>(list); // 创建一个新的列表，避免外部修改
    }

    public synchronized void setData(List<SimilarBean> newList) {
        if (newList == null || newList.isEmpty()) {
            return;
        }
        DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new DiffCallback(this.list, newList));
        this.list = new ArrayList<>(newList);
        diffResult.dispatchUpdatesTo(this);
    }

    @NonNull
    @Override
    public SimilarPhotosAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_similar_photo_recy_list, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull SimilarPhotosAdapter.ViewHolder holder, int position) {
        try {
            if (position >= 0 && position < list.size()) {
                SimilarBean similarBean = list.get(position);
                holder.textView.setText("Group " + (position + 1));
                ItemSimilarAdapter adapter = new ItemSimilarAdapter(similarBean.getItems(), this);
                holder.recyclerView.setLayoutManager(new GridLayoutManager(holder.itemView.getContext(), 3));
                holder.recyclerView.setAdapter(adapter);
            } else {
                ToastUtil.showLongToast(context, "There are no similar pictures available");
            }
        }catch (Exception e){
            Log.e("SimilarPhotosAdapter", "Exception in onBindViewHolder: " + e.getMessage(), e);
        }
    }

    public List<SimilarBean> getSelectedItems() {
        List<SimilarBean> selectedItems = new ArrayList<>();
        for (SimilarBean group : list) {
            for (SimilarBean item : group.getItems()) {
                if (item.isSelect()) {
                    selectedItems.add(item);
                }
            }
        }
        return selectedItems;
    }

//    public void removeSelectedItems() {
//        for (SimilarBean group : list) {
//            group.getItems().removeIf(item -> item.isSelect());
//        }
//        list.removeIf(group -> group.getItems().isEmpty());
//        notifyDataSetChanged();
//    }

//    public int calculateSelectedItemsSize() {
//        int totalSize = 0;
//        for (SimilarBean group : list) {
//            for (SimilarBean item : group.getItems()) {
//                if (item.isSelect()) {
//                    totalSize += item.getSize();
//                }
//            }
//        }
//        return totalSize;
//    }

    @Override
    public int getItemCount() {
        int size = list == null ? 0 : list.size();
        return size;
    }

    public synchronized void updateItem(SimilarBean updatedBean, int position) {
        if (position >= 0 && position < list.size()) {
            SimilarBean group = list.get(position);
            for (SimilarBean item : group.getItems()) {
                if (item.getUrl().equals(updatedBean.getUrl())) {
                    item.setSelect(updatedBean.isSelect());
                    break;
                }
            }
            notifyItemChanged(position);
        } else {
            Log.e("SimilarPhotosAdapter", "Invalid position: " + position + ", list size: " + list.size());
        }
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView textView;
        RecyclerView recyclerView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            recyclerView = itemView.findViewById(R.id.item_similar_photos_recy);
            textView = itemView.findViewById(R.id.item_similar_photos_text);
        }
    }

    private static class DiffCallback extends DiffUtil.Callback {
        private final List<SimilarBean> oldList;
        private final List<SimilarBean> newList;

        public DiffCallback(List<SimilarBean> oldList, List<SimilarBean> newList) {
            this.oldList = oldList;
            this.newList = newList;
        }

        @Override
        public int getOldListSize() {
            return oldList.size();
        }

        @Override
        public int getNewListSize() {
            return newList.size();
        }

        @Override
        public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
            return oldList.get(oldItemPosition).getGroupID().equals(newList.get(newItemPosition).getGroupID());
        }

        @Override
        public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
            return oldList.get(oldItemPosition).equals(newList.get(newItemPosition));
        }
    }
}
