package com.ar.ardrawingboard.ui.adapter;

import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

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

import com.ar.ardrawingboard.R;
import com.ar.ardrawingboard.ui.activity.BoardActivity;
import com.ar.ardrawingboard.room.AppDatabase;
import com.ar.ardrawingboard.room.BoardEntry;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;

import java.util.List;
import java.util.concurrent.Executors;

public class ImportFragmentAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int TYPE_HEADER = 0;
    private static final int TYPE_ENTRY = 1;

    private List<BoardEntry> boardItems;
    private final Activity host;
    private final OnHeaderClickListener headerClickCallback;

    public ImportFragmentAdapter(List<BoardEntry> boardItems, Activity host, OnHeaderClickListener headerClickCallback) {
        this.boardItems = boardItems;
        this.host = host;
        this.headerClickCallback = headerClickCallback;
    }

    public interface OnHeaderClickListener {
        void onHeaderClick();
    }

    @Override
    public int getItemViewType(int position) {
        return position == 0 ? TYPE_HEADER : TYPE_ENTRY;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parentView, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parentView.getContext());

        if (viewType == TYPE_HEADER) {
            View headerLayout = inflater.inflate(R.layout.item_special_view, parentView, false);
            return new HeaderHolder(headerLayout);
        } else {
            View itemLayout = inflater.inflate(R.layout.item_import, parentView, false);
            return new EntryHolder(itemLayout);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int pos) {
        if (getItemViewType(pos) == TYPE_HEADER) {
            HeaderHolder header = (HeaderHolder) viewHolder;
            header.itemView.setOnClickListener(v -> {
                if (headerClickCallback != null) {
                    headerClickCallback.onHeaderClick();
                }
            });
        } else {
            EntryHolder holder = (EntryHolder) viewHolder;
            BoardEntry item = boardItems.get(pos - 1);

            holder.bindItem(item);

            holder.imagePreview.setOnClickListener(v -> {
                Intent intent = new Intent(host, BoardActivity.class);
                intent.putExtra("imagePath", item.getPath());
                host.startActivity(intent);
            });
        }
    }

    @Override
    public int getItemCount() {
        return boardItems != null ? boardItems.size() + 1 : 1;
    }

    public void refreshItems(List<BoardEntry> updatedList) {
        this.boardItems = updatedList;
        notifyDataSetChanged();
    }

    static class HeaderHolder extends RecyclerView.ViewHolder {
        public HeaderHolder(@NonNull View itemView) {
            super(itemView);
        }
    }

    class EntryHolder extends RecyclerView.ViewHolder {
        ImageView imagePreview;
        ImageView favoriteToggle;

        public EntryHolder(@NonNull View itemView) {
            super(itemView);
            imagePreview = itemView.findViewById(R.id.image_view);
            favoriteToggle = itemView.findViewById(R.id.btn_favorite);
        }

        void bindItem(BoardEntry data) {
            String imgPath = data.getPath();

            Glide.with(host)
                    .load(imgPath)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .transform(new CenterCrop(),new RoundedCorners(32))
                    .placeholder(R.mipmap.placeholder)
                    .error(R.mipmap.placeholder)
                    .into(imagePreview);

            favoriteToggle.setImageResource(data.isFavorite() ? R.drawable.like : R.drawable.un_like);

            favoriteToggle.setOnClickListener(view -> {
                boolean toggled = !data.isFavorite();
                data.setFavorite(toggled);

                Executors.newSingleThreadExecutor().execute(() ->
                        AppDatabase.getInstance(host).boardEntryDao().update(data)
                );

                int currentPos = getAdapterPosition();
                if (currentPos != RecyclerView.NO_POSITION) {
                    notifyItemChanged(currentPos);
                }
            });
        }
    }
}