package com.nadi.player.nativeplayer.channels;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

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

import com.nadi.player.R;

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

/**
 * Flat RecyclerView adapter for the right-side channel overlay.
 *
 * Performance notes (important for IPTV use on low-end TV boxes):
 *   • Holds plain {@code List<Channel>} — no LiveData / Flow overhead.
 *   • Uses DiffUtil for filter() / category switches; the initial bind
 *     is a plain {@code notifyDataSetChanged} so first paint stays cheap.
 *   • Row height is fixed at 64dp so we call setHasFixedSize(true) on
 *     the host RecyclerView and skip relayout passes.
 *   • No network image calls — placeholder letter logo for now.
 */
public final class ChannelListAdapter
        extends RecyclerView.Adapter<ChannelListAdapter.ChannelVH> {

    public interface OnChannelClick {
        void onChannelClick(Channel channel, int position);
    }

    private final List<Channel> items = new ArrayList<>();
    private final OnChannelClick listener;
    private int selectedPosition = -1;

    public ChannelListAdapter(OnChannelClick listener) {
        this.listener = listener;
        setHasStableIds(true);
    }

    @Override
    public long getItemId(int position) {
        // Channel number is unique within a playlist, so it's a safe
        // stable ID and prevents flicker on filter changes.
        return items.get(position).number;
    }

    public void submit(List<Channel> next) {
        if (items.isEmpty()) {
            items.addAll(next);
            notifyDataSetChanged();
            return;
        }
        DiffUtil.DiffResult diff = DiffUtil.calculateDiff(new DiffUtil.Callback() {
            @Override public int getOldListSize() { return items.size(); }
            @Override public int getNewListSize() { return next.size(); }
            @Override public boolean areItemsTheSame(int o, int n) {
                return items.get(o).number == next.get(n).number;
            }
            @Override public boolean areContentsTheSame(int o, int n) {
                Channel a = items.get(o), b = next.get(n);
                return a.number == b.number
                        && a.favorite == b.favorite
                        && eq(a.name, b.name)
                        && eq(a.epgNow, b.epgNow)
                        && eq(a.epgNext, b.epgNext);
            }
        }, /* detectMoves = */ false);
        items.clear();
        items.addAll(next);
        diff.dispatchUpdatesTo(this);
    }

    /** Tag a row as "currently playing". Pass -1 to clear. */
    public void setSelectedChannelNumber(int channelNumber) {
        int old = selectedPosition;
        selectedPosition = -1;
        for (int i = 0; i < items.size(); i++) {
            if (items.get(i).number == channelNumber) {
                selectedPosition = i;
                break;
            }
        }
        if (old != selectedPosition) {
            if (old >= 0) notifyItemChanged(old);
            if (selectedPosition >= 0) notifyItemChanged(selectedPosition);
        }
    }

    public int indexOfChannel(int channelNumber) {
        for (int i = 0; i < items.size(); i++) {
            if (items.get(i).number == channelNumber) return i;
        }
        return -1;
    }

    public Channel get(int position) {
        if (position < 0 || position >= items.size()) return null;
        return items.get(position);
    }

    @NonNull
    @Override
    public ChannelVH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_channel, parent, false);
        return new ChannelVH(v);
    }

    @Override
    public void onBindViewHolder(@NonNull ChannelVH h, int position) {
        Channel c = items.get(position);
        h.number.setText(String.format(Locale.US, "%d", c.number));
        h.logo.setText(c.logoLetter());
        h.name.setText(c.name);
        boolean hasNow = c.epgNow != null && !c.epgNow.isEmpty();
        h.epgNow.setText(hasNow ? c.epgNow : "");
        h.epgNow.setVisibility(hasNow ? View.VISIBLE : View.GONE);
        boolean hasNext = c.epgNext != null && !c.epgNext.isEmpty();
        h.epgNext.setText(hasNext ? "Next · " + c.epgNext : "");
        h.epgNext.setVisibility(hasNext ? View.VISIBLE : View.GONE);
        h.fav.setVisibility(c.favorite ? View.VISIBLE : View.GONE);
        h.itemView.setSelected(position == selectedPosition);
        h.itemView.setOnClickListener(v -> {
            if (listener != null) listener.onChannelClick(c, h.getBindingAdapterPosition());
        });
    }

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

    static final class ChannelVH extends RecyclerView.ViewHolder {
        final TextView number;
        final TextView logo;
        final TextView name;
        final TextView epgNow;
        final TextView epgNext;
        final ImageView fav;
        ChannelVH(@NonNull View itemView) {
            super(itemView);
            number  = itemView.findViewById(R.id.channel_number);
            logo    = itemView.findViewById(R.id.channel_logo_letter);
            name    = itemView.findViewById(R.id.channel_name);
            epgNow  = itemView.findViewById(R.id.channel_epg_now);
            epgNext = itemView.findViewById(R.id.channel_epg_next);
            fav     = itemView.findViewById(R.id.channel_fav);
        }
    }

    private static boolean eq(String a, String b) {
        return a == null ? b == null : a.equals(b);
    }
}
