package com.app.input.personalised.board.listhelpers;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.app.input.personalised.board.R;
import com.app.input.personalised.board.databean.KeyboardTheme;
import com.app.input.personalised.board.boartactivity.FavoriteThemeActivity;
import com.app.input.personalised.board.boartactivity.ThemeDetailActivity;
import com.app.input.personalised.board.helpers.AppUtils;
import com.bumptech.glide.Glide;

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

public class FavoriteCardListAdapter extends RecyclerView.Adapter<FavoriteCardListAdapter.FavoriteCardViewHolder> {

    private Context mContext;
    private List<KeyboardTheme> mFavoriteList = new ArrayList<>();

    public FavoriteCardListAdapter(Context context) {
        mContext = context;
    }

    public void setFavoriteList(List<KeyboardTheme> favoriteList) {
        this.mFavoriteList = favoriteList != null ? favoriteList : new ArrayList<>();
        notifyDataSetChanged();
    }

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

    @Override
    public void onBindViewHolder(@NonNull FavoriteCardViewHolder holder, int position) {
        // 每个卡片显示所有收藏的前2-4张预览图
        int totalCount = mFavoriteList.size();
        int imageCount = Math.min(totalCount, 4);
        
        // 显示收藏数量
        holder.tvFavoriteCount.setText(totalCount + " " + mContext.getString(R.string.favorite).toLowerCase() + "s");
        
        // 隐藏所有图片容器
        holder.frameImage1.setVisibility(View.GONE);
        holder.frameImage2.setVisibility(View.GONE);
        holder.frameImage3.setVisibility(View.GONE);
        holder.frameImage4.setVisibility(View.GONE);
        
        // 如果有收藏，显示预览图
        if (imageCount > 0) {
            // 显示图片区域，隐藏空状态
            holder.layoutImages.setVisibility(View.VISIBLE);
            holder.layoutEmptyHint.setVisibility(View.GONE);
            
            // 根据数量显示图片
            FrameLayout[] frames = {holder.frameImage1, holder.frameImage2, holder.frameImage3, holder.frameImage4};
            ImageView[] imageViews = {holder.ivImage1, holder.ivImage2, holder.ivImage3, holder.ivImage4};
            
            for (int i = 0; i < imageCount; i++) {
                KeyboardTheme item = mFavoriteList.get(i);
                FrameLayout frame = frames[i];
                ImageView imageView = imageViews[i];
                
                frame.setVisibility(View.VISIBLE);
                // 设置权重，确保图片平均分配空间
                ViewGroup.LayoutParams params = frame.getLayoutParams();
                if (params instanceof LinearLayout.LayoutParams) {
                    ((LinearLayout.LayoutParams) params).weight = 1.0f;
                }
                
                String thumbGif = item.getThumbGif();
                String thumb = item.getThumbUrl();
                
                if (thumbGif != null && !thumbGif.isEmpty()) {
                    AppUtils.INSTANCE.loadWepJif(mContext, thumbGif, imageView);
                } else if (thumb != null && !thumb.isEmpty()) {
                    Glide.with(mContext)
                            .load(thumb)
                            .placeholder(R.drawable.placeholder)
                            .error(R.drawable.placeholder)
                            .centerCrop()
                            .into(imageView);
                } else {
                    imageView.setImageResource(R.drawable.placeholder);
                }
                
                // 设置预览图点击事件，跳转到对应的详情页
                final KeyboardTheme clickItem = item;
                frame.setOnClickListener(v -> {
                    openDetailActivity(clickItem);
                });
            }
            
            // 动态调整父布局的weightSum，确保图片平均分配
            holder.layoutImages.setWeightSum(imageCount);
        } else {
            // 没有收藏时，隐藏图片区域，显示空状态提示
            holder.layoutImages.setVisibility(View.GONE);
            holder.layoutEmptyHint.setVisibility(View.VISIBLE);
        }
        
        // 点击卡片跳转到收藏列表界面
        holder.cardView.setOnClickListener(v -> {
            Intent intent = new Intent(mContext, FavoriteThemeActivity.class);
            mContext.startActivity(intent);
        });
        
        // 点击"查看全部"也跳转到收藏列表界面
        holder.layoutSeeAll.setOnClickListener(v -> {
            Intent intent = new Intent(mContext, FavoriteThemeActivity.class);
            mContext.startActivity(intent);
        });
    }

    private void openDetailActivity(KeyboardTheme item) {
        Intent intent = new Intent(mContext, ThemeDetailActivity.class);
        intent.putExtra(ThemeDetailActivity.SOURCE_KEY, item);
        intent.putExtra(ThemeDetailActivity.DISPLAY_URL_KEY, item.getImgPath());
        intent.putExtra(ThemeDetailActivity.ZIP_URL_KEY, item.getZipPath());
        intent.putExtra(ThemeDetailActivity.NAME_KEY, item.getTitleName());
        intent.putExtra(ThemeDetailActivity.GIF_KEY, item.getImgGif());
        String intent_thumb;
        String thumbGif = item.getThumbGif();
        if (thumbGif != null && !thumbGif.isEmpty()) {
            intent_thumb = thumbGif;
        } else {
            intent_thumb = item.getThumbUrl();
        }
        intent.putExtra(ThemeDetailActivity.THUMB_KEY, intent_thumb);
        mContext.startActivity(intent);
    }

    @Override
    public int getItemCount() {
        // 始终显示一个卡片，即使没有收藏
        return 1;
    }

    public static class FavoriteCardViewHolder extends RecyclerView.ViewHolder {
        CardView cardView;
        LinearLayout layoutImages;
        LinearLayout layoutSeeAll;
        FrameLayout frameImage1, frameImage2, frameImage3, frameImage4;
        ImageView ivImage1, ivImage2, ivImage3, ivImage4;
        TextView tvCardTitle, tvSeeAll, tvFavoriteCount;
        LinearLayout layoutEmptyHint;

        public FavoriteCardViewHolder(@NonNull View itemView) {
            super(itemView);
            cardView = itemView.findViewById(R.id.card_view);
            layoutImages = itemView.findViewById(R.id.layout_images);
            layoutSeeAll = itemView.findViewById(R.id.layout_see_all);
            frameImage1 = itemView.findViewById(R.id.frame_image1);
            frameImage2 = itemView.findViewById(R.id.frame_image2);
            frameImage3 = itemView.findViewById(R.id.frame_image3);
            frameImage4 = itemView.findViewById(R.id.frame_image4);
            ivImage1 = itemView.findViewById(R.id.iv_image1);
            ivImage2 = itemView.findViewById(R.id.iv_image2);
            ivImage3 = itemView.findViewById(R.id.iv_image3);
            ivImage4 = itemView.findViewById(R.id.iv_image4);
            tvCardTitle = itemView.findViewById(R.id.tv_card_title);
            tvSeeAll = itemView.findViewById(R.id.tv_see_all);
            tvFavoriteCount = itemView.findViewById(R.id.tv_favorite_count);
            layoutEmptyHint = itemView.findViewById(R.id.layout_empty_hint);
        }
    }
}
