package com.kaixed.kchat.view.adapter;

import static com.kaixed.kchat.utils.Constants.TYPE_ITEM_MINE;
import static com.kaixed.kchat.utils.Constants.TYPE_ITEM_OTHER;
import static com.kaixed.kchat.utils.Constants.TYPE_MESSAGE_WITHDRAW;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.text.SpannableString;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.window.layout.WindowMetrics;
import androidx.window.layout.WindowMetricsCalculator;

import com.kaixed.kchat.R;
import com.kaixed.kchat.database.entity.Messages;
import com.kaixed.kchat.database.ObjectBox;
import com.kaixed.kchat.database.UserManager;
import com.kaixed.kchat.utils.ImageSpanUtil;

import java.util.LinkedList;

import io.objectbox.Box;

/**
 * @Author: kaixed
 * @Date: 2024/5/4 22:48
 * @Description: TODO
 */
public class ChatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private final LinkedList<Messages> messages;
    private final Context mContext;

    public ChatAdapter(Context mContext, LinkedList<Messages> messages) {
        this.messages = messages;
        this.mContext = mContext;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder viewHolder;
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        if (viewType == TYPE_ITEM_MINE) {
            View view = inflater.inflate(R.layout.chat_recycle_item_mine, parent, false);
            viewHolder = new MineViewHolder(view);
        } else if (viewType == TYPE_ITEM_OTHER) {
            View view = inflater.inflate(R.layout.chat_recycle_item_other, parent, false);
            viewHolder = new OtherViewHolder(view);
        } else {
            View view = inflater.inflate(R.layout.chat_recycle_item_withdraw, parent, false);
            viewHolder = new WithdrawViewHolder(view);
        }
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

        Messages singleMessage = messages.get(position);
        if (singleMessage == null) {
            return;
        }
        if (holder.getItemViewType() == TYPE_ITEM_MINE) {
            MineViewHolder mineViewHolder = (MineViewHolder) holder;
            SpannableString spannableString = ImageSpanUtil.setEmojiSpan(mContext, singleMessage.getContent(), (int) mineViewHolder.mTvContent.getTextSize());

            mineViewHolder.mTvContent.setText(spannableString);

            mineViewHolder.mTvContent.setOnLongClickListener(v -> {
                showPopupWindow(v, position);
                return true;
            });

        } else if (holder.getItemViewType() == TYPE_ITEM_OTHER) {
            OtherViewHolder otherViewHolder = (OtherViewHolder) holder;

            SpannableString spannableString = ImageSpanUtil.setEmojiSpan(mContext, singleMessage.getContent(), (int) otherViewHolder.mTvContent.getTextSize());

            otherViewHolder.mTvContent.setText(spannableString);
            otherViewHolder.mTvContent.setOnLongClickListener(v -> {
                showPopupWindow(v, position);
                return true;
            });
        } else {
            WithdrawViewHolder mineViewHolder = (WithdrawViewHolder) holder;
            mineViewHolder.bindData(singleMessage.getSenderId());
        }

    }

    /**
     * 用来显示消息长按弹窗
     */
    private void showPopupWindow(@NonNull View textView, int position) {
        @SuppressLint("InflateParams") View popupView = LayoutInflater.from(mContext).inflate(R.layout.popwindows, null);

        PopupWindow popupWindow = new PopupWindow(popupView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable());


        popupView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupWidth = popupView.getMeasuredWidth();
        int popupHeight = popupView.getMeasuredHeight();

        int anchorWidth = textView.getWidth();
        int anchorHeight = textView.getHeight();
        int offsetX = (anchorWidth - popupWidth) / 2;

        int offset = 15;

        ImageView mIvArrowUp = popupView.findViewById(R.id.iv_arrow_up);
        ImageView mIvArrowDown = popupView.findViewById(R.id.iv_arrow_down);

        if (getDistanceFromTop(textView) > anchorHeight) {
            popupWindow.showAsDropDown(textView, offsetX, -offset - anchorHeight - popupHeight);
            mIvArrowUp.setVisibility(View.GONE);
            mIvArrowDown.setVisibility(View.VISIBLE);
        } else {
            popupWindow.showAsDropDown(textView, offsetX, 10);
            mIvArrowUp.setVisibility(View.VISIBLE);
            mIvArrowDown.setVisibility(View.GONE);
        }

        ImageView mIvWithdraw = popupView.findViewById(R.id.iv_withdraw);

        mIvWithdraw.setOnClickListener(v -> {
            messages.get(position).setStatus("withdraw");
            updateDb(messages.get(position));
            notifyItemChanged(position);

            popupWindow.dismiss();
        });
    }

    private void updateDb(Messages messages) {
        Box<Messages> messagesBox = ObjectBox.get().boxFor(Messages.class);
        messagesBox.put(messages);
    }

    private int getDistanceFromTop(View view) {
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        //location[0]指的是横向距离
        return location[1];
    }

    private int getDistanceFromBottom(@NonNull View view) {
        // 获取控件在屏幕上的位置
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        // 获取屏幕高度
        WindowMetrics windowMetrics = WindowMetricsCalculator.getOrCreate().computeCurrentWindowMetrics(mContext);
        int screenHeight = windowMetrics.getBounds().height();
        // 计算控件底部到屏幕底部的距离
        int viewBottom = location[1] + view.getHeight();
        return screenHeight - viewBottom;
    }

    @Override
    public int getItemViewType(int position) {
        String curUser = UserManager.getInstance().getUsername();
        if ("withdraw".equals(messages.get(position).getStatus())) {
            return TYPE_MESSAGE_WITHDRAW;
        }
        return curUser.equals(messages.get(position).getSenderId()) ? TYPE_ITEM_MINE : TYPE_ITEM_OTHER;
    }

    @Override
    public int getItemCount() {
        return messages.isEmpty() ? 0 : messages.size();
    }

    static class MineViewHolder extends RecyclerView.ViewHolder {
        private final TextView mTvContent;

        public MineViewHolder(@NonNull View itemView) {
            super(itemView);
            mTvContent = itemView.findViewById(R.id.tv_mine_content);
        }

        private void bindData(Messages singleMessage) {
            mTvContent.setText(singleMessage.getContent());
        }
    }

    static class OtherViewHolder extends RecyclerView.ViewHolder {
        private final TextView mTvContent;

        public OtherViewHolder(@NonNull View itemView) {
            super(itemView);
            mTvContent = itemView.findViewById(R.id.tv_other_content);
        }

        private void bindData(Messages singleMessage) {
            mTvContent.setText(singleMessage.getContent());
        }
    }

    static class WithdrawViewHolder extends RecyclerView.ViewHolder {
        private final TextView mTvNickname;

        public WithdrawViewHolder(@NonNull View itemView) {
            super(itemView);
            mTvNickname = itemView.findViewById(R.id.tv_user_nickname);
        }

        private void bindData(String nickname) {
            mTvNickname.setText(nickname);
        }
    }
}
