package com.wall.photography.picture.Project;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

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

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.wall.photography.picture.R;
import com.wall.photography.picture.Data.Data;
import com.wall.photography.picture.Connect.ItemClick;
import com.wall.photography.picture.tool.CommonUtils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

public class List extends RecyclerView.Adapter<List.MyViewHolder> {


    private java.util.List<Data> dataInfo = new ArrayList<>();

    private ItemClick onItemClick;
    private WeakReference<Context> weakReference;
    private int itemHeight;
    private boolean showSpace = false;


    public void setInfoWallpaperListener(ItemClick onItemClick) {
        this.onItemClick = onItemClick;
    }

    public List(Context myCon, int itemHeight, boolean show) {
        weakReference = new WeakReference<>(myCon);
        this.itemHeight = itemHeight;
        showSpace = show;
    }

    public void setDataInfo(java.util.List<Data> dataInfo) {
        this.dataInfo = dataInfo;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        Context context = weakReference.get();
        if (context != null) {
            View itemView = LayoutInflater.from(context).inflate(R.layout.project_list, parent, false);
            ImageView imageView = itemView.findViewById(R.id.wallpaper);
            ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
            layoutParams.height = itemHeight;
            imageView.setLayoutParams(layoutParams);
            return new MyViewHolder(itemView);
        }
        return null;


    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        Data info = dataInfo.get(position);
        ImageView imageView = holder.getImageView();
        String previewUrl400 = info.getPreviewUrl400();
        String previewUrl200 = info.getPreviewUrl200();
        RelativeLayout item = holder.getLayout();
        String imId = info.getImId();
        int curheight;
        View spaceView = holder.getSpaceView();
        if (showSpace && position == dataInfo.size() - 1) {
            spaceView.setVisibility(View.VISIBLE);
        } else {
            spaceView.setVisibility(View.GONE);
        }


        MultiTransformation<Bitmap> multiTransformation = new MultiTransformation<>(
                new CenterCrop(),
                new RoundedCornersTransformation(CommonUtils.dp2Px(12), 0) // 圆角效果
        );
        RequestOptions options = new RequestOptions()
                .format(DecodeFormat.PREFER_RGB_565);
        Context context = weakReference.get();
        if (context != null) {
            Log.d("-----------","----------------Glide");
            Glide.with(context)
                    .asDrawable()
                    .thumbnail(Glide.with(context)
                            .load(previewUrl200)
                            .transform(multiTransformation))
                    .load(previewUrl400)
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, @Nullable Object model, @NonNull Target<Drawable> target, boolean isFirstResource) {
                            android.util.Log.e("ImageLoad", "Failed to load image: " + model + ", Error: " + (e != null ? e.getMessage() : "Unknown"));
                            if (e != null) {
                                e.logRootCauses("ImageLoad");
                            }
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(@NonNull Drawable resource, @NonNull Object model, Target<Drawable> target, @NonNull DataSource dataSource, boolean isFirstResource) {
                            android.util.Log.d("ImageLoad", "Successfully loaded image from: " + dataSource);
                            return false;
                        }
                    })
                    .placeholder(R.drawable.image_load_placeholder)
                    .error(R.drawable.image_load_fail)
                    .transform(multiTransformation)
                    .into(imageView);
        }


        item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemClick != null) {
                    onItemClick.onItemClickAction(info);
                }

            }
        });

        // 隐藏图片上的标签文字
        holder.tagText.setVisibility(View.GONE);

    }

    private void setupTagText(MyViewHolder holder, int position) {
        if (position < 0 || position >= dataInfo.size()) {
            holder.tagText.setVisibility(View.GONE);
            return;
        }
        
        Data info = dataInfo.get(position);
        String categoryName = info.getCategoryName();
        
        // 根据真实分类名称映射到标签
        String tagText = getTagForCategory(categoryName);
        
        if (tagText != null && !tagText.isEmpty()) {
            final String finalTagText = tagText;
            
            holder.tagText.setText(finalTagText);
            holder.tagText.setVisibility(View.VISIBLE);
            
            // 标签点击事件
            holder.tagText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onItemClick != null && holder.getAdapterPosition() != RecyclerView.NO_POSITION) {
                        Data itemInfo = dataInfo.get(holder.getAdapterPosition());
                        onItemClick.onTagClick(finalTagText, itemInfo);
                    }
                }
            });
        } else {
            holder.tagText.setVisibility(View.GONE);
        }
    }
    
    /**
     * 根据分类名称获取对应的标签
     */
    private String getTagForCategory(String categoryName) {
        if (categoryName == null) {
            return null;
        }
        
        // 将分类映射到标签（分类名是JSON文件名去掉.json后缀）
        switch (categoryName) {
            case "Featuredsearch":
                return "Feature";
            case "Animalssearch":
                return "Animal";
            case "Filmsearch":
                return "Film";
            default:
                return null;
        }
    }

    @Override
    public int getItemCount() {
        return dataInfo.size();
    }

    @Override
    public void onViewRecycled(@NonNull MyViewHolder holder) {
        super.onViewRecycled(holder);


    }


    private static DiffUtil.ItemCallback<Data> diff = new DiffUtil.ItemCallback<Data>() {


        @Override
        public boolean areItemsTheSame(@NonNull Data oldItem, @NonNull Data newItem) {
            return oldItem.getImId().equals(newItem.getImId());
        }

        @Override
        public boolean areContentsTheSame(@NonNull Data oldItem, @NonNull Data newItem) {
            return oldItem.getImId().equals(newItem.getImId());
        }
    };

    private static class MyCallback extends DiffUtil.Callback {
        private java.util.List<Data> mOldList;
        private java.util.List<Data> mNewList;

        public MyCallback(java.util.List<Data> oldList, java.util.List<Data> newList) {
            mOldList = oldList;
            mNewList = newList;
        }

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

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

        @Override
        public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
            return mOldList.get(oldItemPosition).getImId().equals(mNewList.get(newItemPosition).getImId());
        }

        @Override
        public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
            return mOldList.get(oldItemPosition).getImId().equals(mNewList.get(newItemPosition).getImId());
        }
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {

        private ImageView imageView;
        private RelativeLayout layout;

        private View spaceView;
        private TextView tagText;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.wallpaper);
            layout = itemView.findViewById(R.id.layout);
            spaceView = itemView.findViewById(R.id.space_view);
            tagText = itemView.findViewById(R.id.tag_text);
        }

        public RelativeLayout getLayout() {
            return layout;
        }

        public ImageView getImageView() {
            return imageView;
        }

        public View getSpaceView() {
            return spaceView;
        }
    }

}
