package com.miraclegarden.smsmessage.Activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.miraclegarden.library.app.MiracleGardenActivity;
import com.miraclegarden.smsmessage.R;
import com.miraclegarden.smsmessage.comm.CommonAdapter;
import com.miraclegarden.smsmessage.comm.ViewHolder;
import com.miraclegarden.smsmessage.databinding.ActivityMmpDetailBinding;
import com.miraclegarden.smsmessage.mmp.MmpClaim;
import com.miraclegarden.smsmessage.mmp.MmpPacket;
import com.miraclegarden.smsmessage.mmp.MmpPacketStore;

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

/**
 * 单个红包领取排行（数据优先展示）。
 */
public class MmpDetailActivity extends MiracleGardenActivity<ActivityMmpDetailBinding>
        implements MmpPacketStore.Listener {

    public static final String EXTRA_PACKET_ID = "packetId";

    private String packetId;
    private final List<MmpClaim> claims = new ArrayList<>();
    private CommonAdapter<MmpClaim> adapter;
    private final Handler handler = new Handler(Looper.getMainLooper());
    private final Runnable refreshRunnable = this::reload;
    private double bestAmount = -1;
    private double worstAmount = -1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        packetId = getIntent().getStringExtra(EXTRA_PACKET_ID);
        if (TextUtils.isEmpty(packetId)) {
            finish();
            return;
        }
        initView();
        reload();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MmpPacketStore.addListener(this);
        reload();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MmpPacketStore.removeListener(this);
        handler.removeCallbacks(refreshRunnable);
    }

    @Override
    public void onMmpPacketsChanged() {
        runOnUiThread(this::reload);
    }

    private void initView() {
        binding.backIv.setOnClickListener(v -> finish());
        binding.recyclerview.setLayoutManager(new LinearLayoutManager(this));
        adapter = new CommonAdapter<MmpClaim>(this, R.layout.item_mmp_claim, claims) {
            @Override
            public void convert(ViewHolder holder, MmpClaim claim, int index) {
                holder.setText(R.id.tv_rank, String.valueOf(claim.rank > 0 ? claim.rank : index + 1));
                holder.setText(R.id.tv_nickname, claim.nickname != null ? claim.nickname : "?");
                TextView userIdView = holder.getView(R.id.tv_user_id);
                if (!TextUtils.isEmpty(claim.userId)) {
                    userIdView.setVisibility(View.VISIBLE);
                    userIdView.setText("用户ID " + claim.userId);
                } else {
                    userIdView.setVisibility(View.GONE);
                    userIdView.setText("");
                }
                TextView poolIdView = holder.getView(R.id.tv_pool_id);
                if (!TextUtils.isEmpty(claim.poolId)) {
                    poolIdView.setVisibility(View.VISIBLE);
                    poolIdView.setText("领取ID " + claim.poolId);
                } else {
                    poolIdView.setVisibility(View.GONE);
                    poolIdView.setText("");
                }
                holder.setText(R.id.tv_amount, claim.amountText != null
                        ? claim.amountText
                        : String.format(Locale.US, "%.2f", claim.amount));
                holder.setText(R.id.tv_time,
                        TextUtils.isEmpty(claim.claimTime) ? "-" : claim.claimTime);

                TextView tag = holder.getView(R.id.tv_tag);
                boolean isBest = claims.size() > 1 && bestAmount >= 0
                        && Math.abs(claim.amount - bestAmount) < 0.0001;
                boolean isWorst = claims.size() > 1 && worstAmount >= 0
                        && Math.abs(claim.amount - worstAmount) < 0.0001
                        && Math.abs(bestAmount - worstAmount) > 0.0001;
                if (isBest) {
                    tag.setVisibility(View.VISIBLE);
                    tag.setText("最高");
                    tag.setTextColor(Color.parseColor("#047857"));
                    holder.itemView.setBackgroundColor(Color.parseColor("#ECFDF5"));
                } else if (isWorst) {
                    tag.setVisibility(View.VISIBLE);
                    tag.setText("最低");
                    tag.setTextColor(Color.parseColor("#B45309"));
                    holder.itemView.setBackgroundColor(Color.parseColor("#FFFBEB"));
                } else {
                    tag.setVisibility(View.GONE);
                    holder.itemView.setBackgroundColor(Color.WHITE);
                }
            }
        };
        binding.recyclerview.setAdapter(adapter);
    }

    private void reload() {
        MmpPacket packet = MmpPacketStore.getPacket(this, packetId);
        if (packet == null) {
            binding.tvTitle.setText("红包详情");
            binding.tvHeaderMoney.setText("-");
            binding.tvSub.setText("记录不存在或已清空");
            binding.tvBestName.setText("-");
            binding.tvBestAmt.setText("-");
            binding.tvWorstName.setText("-");
            binding.tvWorstAmt.setText("-");
            claims.clear();
            adapter.notifyDataSetChanged();
            binding.emptyLy.setVisibility(View.VISIBLE);
            binding.recyclerview.setVisibility(View.GONE);
            return;
        }
        binding.tvTitle.setText(packet.displayTitle());
        binding.tvHeaderMoney.setText(String.format(Locale.US, "%.2f",
                packet.sumClaimed > 0 ? packet.sumClaimed : parseDouble(packet.total)));

        StringBuilder sub = new StringBuilder();
        if (!TextUtils.isEmpty(packet.packetId)) {
            sub.append("ID ").append(packet.packetId);
        }
        if (!TextUtils.isEmpty(packet.issuedAt)) {
            if (sub.length() > 0) {
                sub.append(" · ");
            }
            sub.append("发放 ").append(packet.issuedAt);
        }
        if (!TextUtils.isEmpty(packet.expiresAt)) {
            if (sub.length() > 0) {
                sub.append(" · ");
            }
            sub.append("到期 ").append(packet.expiresAt);
        }
        if (sub.length() > 0) {
            sub.append(" · ");
        }
        sub.append(packet.statusLabel());
        binding.tvSub.setText(sub.toString());

        binding.tvStatPeople.setText(String.valueOf(packet.claimantCount));
        binding.tvStatSum.setText(String.format(Locale.US, "%.2f", packet.sumClaimed));
        binding.tvStatTotal.setText(TextUtils.isEmpty(packet.total) ? "-" : packet.total);

        String hi = packet.finished ? "手气最佳" : "目前最高";
        String lo = packet.finished ? "手气最差" : "目前最低";
        binding.tvBestLab.setText(hi);
        binding.tvWorstLab.setText(lo);
        MmpClaim best = packet.bestClaim();
        MmpClaim worst = packet.worstClaim();
        if (best != null) {
            bestAmount = best.amount;
            binding.tvBestName.setText(formatClaimName(best));
            binding.tvBestAmt.setText(best.amountText != null ? best.amountText
                    : String.format(Locale.US, "%.2f", best.amount));
        } else {
            bestAmount = -1;
            binding.tvBestName.setText("-");
            binding.tvBestAmt.setText("-");
        }
        if (worst != null && packet.claimantCount > 1) {
            worstAmount = worst.amount;
            binding.tvWorstName.setText(formatClaimName(worst));
            binding.tvWorstAmt.setText(worst.amountText != null ? worst.amountText
                    : String.format(Locale.US, "%.2f", worst.amount));
        } else {
            worstAmount = -1;
            binding.tvWorstName.setText("-");
            binding.tvWorstAmt.setText("-");
        }

        claims.clear();
        if (packet.leaderboard != null) {
            claims.addAll(packet.leaderboard);
        }
        adapter.notifyDataSetChanged();
        boolean empty = claims.isEmpty();
        binding.emptyLy.setVisibility(empty ? View.VISIBLE : View.GONE);
        binding.recyclerview.setVisibility(empty ? View.GONE : View.VISIBLE);

        handler.removeCallbacks(refreshRunnable);
        handler.postDelayed(refreshRunnable, 2000);
    }

    private static String formatClaimName(MmpClaim claim) {
        if (claim == null) {
            return "-";
        }
        String nick = claim.nickname != null ? claim.nickname : "?";
        if (!TextUtils.isEmpty(claim.userId)) {
            return nick + "\nID " + claim.userId;
        }
        return nick;
    }

    private static double parseDouble(String s) {
        try {
            return s == null || s.isEmpty() ? 0 : Double.parseDouble(s);
        } catch (NumberFormatException e) {
            return 0;
        }
    }
}
