package com.baidu.ai.sample.adapter;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.text.style.URLSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import io.noties.markwon.AbstractMarkwonPlugin;
import io.noties.markwon.Markwon;
import io.noties.markwon.MarkwonSpansFactory;
import io.noties.markwon.core.CoreProps;

import com.baidu.ai.sample.PicturePreviewActivity;
import com.baidu.ai.sample.R;
import com.baidu.ai.sample.WebViewActivity;
import com.baidu.ai.sample.data.CharacterData;
import com.baidu.ai.sample.data.ChatBean;
import com.baidu.rtc.agent.Constants;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;

import org.commonmark.node.Link;

public class ChatBeanAdapter extends BaseAdapter {
    private static final int TYPE_LEFT = 0;
    private static final int TYPE_RIGHT = 1;
    private static final int TYPE_COUNT = 2;
    private boolean mEnableMarkdown;
    private Context mContext;
    private ArrayList<ChatBean> mData;
    private LayoutInflater mLayoutInflater;
    private Markwon mMarkwon;

    public ChatBeanAdapter() {
    }

    public ChatBeanAdapter(Context context, ArrayList<ChatBean> data, boolean enableMarkdown) {
        mContext = context;
        mEnableMarkdown = enableMarkdown;
        if (mEnableMarkdown) {
            mMarkwon = Markwon.builder(context)
                    .usePlugin(new AbstractMarkwonPlugin() {
                        @Override
                        public void configureSpansFactory(
                                @NonNull MarkwonSpansFactory.Builder builder) {
                            builder.setFactory(Link.class, (configuration, props) -> {
                                String url = CoreProps.LINK_DESTINATION.get(props);
                                return new URLSpan(url) {
                                    @Override
                                    public void onClick(View widget) {
                                        if (!TextUtils.isEmpty(url)) {
                                            handleLinkClick(url);
                                        }
                                    }
                                };
                            });
                        }
                    }).build();
        }

        mLayoutInflater = LayoutInflater.from(context);
        this.mData = data;
    }


    private void handleLinkClick(String url) {
        if (url.startsWith("http") || url.startsWith("https")) {
            // 启动 WebViewActivity 并传递 URL
            Intent intent = new Intent(mContext, WebViewActivity.class);
            intent.putExtra("URL", url);
            mContext.startActivity(intent);
        } else {
            // 处理自定义跳转
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            mContext.startActivity(intent);
        }
    }

    @Override
    public int getCount() {
        return mData != null ? mData.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getViewTypeCount() {
        return TYPE_COUNT;
    }

    @Override
    public int getItemViewType(int pos) {
        ChatBean chat = (ChatBean) mData.get(pos);
        if (chat.isMe) {
            return TYPE_RIGHT;
        }
        return TYPE_LEFT;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
       int type = getItemViewType(position);
       ViewHolder holder = null;
       if (convertView == null) {
           holder = new ViewHolder();
           if (type == TYPE_LEFT) {
                convertView = mLayoutInflater.inflate(R.layout.chat_left, null);
                holder.layoutRes = R.layout.chat_left;
                holder.say = convertView.findViewById(R.id.say_content);
                holder.characterLayout = convertView.findViewById(R.id.character_layout);
                holder.time = convertView.findViewById(R.id.say_time);
                convertView.setTag(holder);
           } else if (type == TYPE_RIGHT) {
               convertView = mLayoutInflater.inflate(R.layout.chat_right, null);
               holder.layoutRes = R.layout.chat_right;
               holder.img = convertView.findViewById(R.id.chat_image);
               holder.say = convertView.findViewById(R.id.say_content);
               holder.time = convertView.findViewById(R.id.say_time);
               convertView.setTag(holder);
           }
       } else {
           if (type == TYPE_LEFT) {
               holder = (ViewHolder) convertView.getTag();
           } else if (type == TYPE_RIGHT) {
               holder = (ViewHolder) convertView.getTag();
           }
       }

        ChatBean chat = (ChatBean) mData.get(position);
        if (holder != null) {
            if (holder.characterLayout != null) {
                holder.characterLayout.setVisibility(View.GONE);
                holder.characterLayout.removeAllViews();
            }
            if (mEnableMarkdown) {
                mMarkwon.setMarkdown((TextView) holder.say, chat.say);
            } else if (chat.hasCustomTag) {
                holder.say.setText(chat.say);

                if (holder.characterLayout != null) {
                    holder.characterLayout.setVisibility(View.VISIBLE);
                    setupCharacterItems(holder.characterLayout, chat);
                }
            } else {
                holder.say.setText(chat.say);
            }
            holder.time.setText(chat.time);

            if (holder.img != null) {
                if (TextUtils.isEmpty(chat.imagePath)) {
                    holder.img.setVisibility(View.GONE);
                } else {
                    holder.img.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (chat.imageUrls == null || chat.imageUrls.length == 0) {
                                return;
                            }
                            Intent intent = new Intent(mContext, PicturePreviewActivity.class);
                            intent.putExtra("ImageUrls", chat.imageUrls);
                            mContext.startActivity(intent);
                        }
                    });
                    holder.img.setVisibility(View.VISIBLE);
                    loadImage(position, holder);
                }
            }
        }
        return convertView;
    }

    private void setupCharacterItems(LinearLayout layout, ChatBean chat) {
        if (chat.characterData == null || chat.characterData.getCustom() == null) {
            return;
        }

        // 添加中文注释
        if (chat.characterData.getCustom().getCommentsCh() != null
                && !chat.characterData.getCustom().getCommentsCh().isEmpty()) {
            for (CharacterData.ChineseComment chineseComment : chat.characterData.getCustom().getCommentsCh()) {
                addCharacterItem(layout, "汉字", chineseComment.getName());
                addCharacterItem(layout, "笔画数", String.valueOf(chineseComment.getStrokenumber()));
                addCharacterItem(layout, "部首", chineseComment.getRadical());
                addCharacterItem(layout, "释义", chineseComment.getComment());
                addCharacterItem(layout, "例句", chineseComment.getExampleSentence());
            }
        }

        // 添加英文注释
        CharacterData.EnglishComment englishComment = chat.characterData.getCustom().getCommentsEn();
        if (englishComment != null) {
            addCharacterItem(layout, "单词", englishComment.getName());
            addCharacterItem(layout, "美式音标", englishComment.getSoundmarkUs());
            addCharacterItem(layout, "英式音标", englishComment.getSoundmarkEn());
            addCharacterItem(layout, "释义", englishComment.getComment());
            addCharacterItem(layout, "例句", englishComment.getExampleSentence());
        }
    }



    private void addCharacterItem(LinearLayout layout, String lable, String value) {
        if (TextUtils.isEmpty(value)) {
            return;
        }

        View item = mLayoutInflater.inflate(R.layout.character_item_layout, null);
        TextView labelTv = item.findViewById(R.id.tv_label);
        TextView valueTv = item.findViewById(R.id.tv_value);
        labelTv.setText(lable);
        valueTv.setText(value);
        layout.addView(item);
    }

    private void loadImage(int position, ViewHolder holder) {
        String imageUrl = mData.get(position).imagePath;
        Glide.with(mContext)
                .load(imageUrl)
                .error(R.drawable.bg_image_loading)
                .placeholder(R.drawable.bg_image_loading)
                .dontAnimate()
                .transform(new RoundedCorners(20))
                .into(holder.img);
    }

    public void updateImage(int position, int error, ArrayList<Constants.MediaGenerateResult> imageResults) {
        if (position >= 0 && position < mData.size()) {
            ChatBean bean = mData.get(position);
            if (imageResults != null && !imageResults.isEmpty()) {
                // 将解码后的图片数据保存到临时文件，供 Glide 加载
                Constants.MediaGenerateResult result = imageResults.get(0);
                String ext = "jpg";
                if (result.mimeType != null) {
                    int slashIdx = result.mimeType.lastIndexOf('/');
                    if (slashIdx >= 0) {
                        ext = result.mimeType.substring(slashIdx + 1);
                    }
                }
                File imgFile = new File(mContext.getCacheDir(), "gen_img_" + System.nanoTime() + "." + ext);
                try {
                    FileOutputStream fos = new FileOutputStream(imgFile);
                    fos.write(result.imageData);
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                bean.imagePath = imgFile.getAbsolutePath();
            }
            if (error == Constants.NO_ERROR) {
                bean.say = "已生成图片。";
            } else {
                bean.say = "生成图片失败，请重试。";
            }
            notifyDataSetChanged();
        }
    }

    public static class ViewHolder {
        LinearLayout characterLayout;
        ImageView img;
        TextView say;
        TextView time;
        int layoutRes;
    }

}

