package com.ar.imagetracear.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.imagetracear.R;
import com.ar.imagetracear.database.AppDatabase;
import com.ar.imagetracear.database.ImageTraceEntry;
import com.ar.imagetracear.activity.ImageTraceActivity;
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 ImportAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int VIEW_TYPE_HEADER = 0;
    private static final int VIEW_TYPE_CONTENT = 1;

    private List<ImageTraceEntry> traceList;
    private final Activity contextActivity;
    private final OnHeaderClickListener headerCallback;

    public ImportAdapter(List<ImageTraceEntry> traceList, Activity contextActivity, OnHeaderClickListener headerCallback) {
        this.traceList = traceList;
        this.contextActivity = contextActivity;
        this.headerCallback = headerCallback;
    }

    public interface OnHeaderClickListener {
        void onHeaderClick();
    }

    @Override
    public int getItemViewType(int index) {
        return index == 0 ? VIEW_TYPE_HEADER : VIEW_TYPE_CONTENT;
    }

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

        if (type == VIEW_TYPE_HEADER) {
            View headerView = inflater.inflate(R.layout.item_special_view, root, false);
            return new HeaderViewHolder(headerView);
        } else {
            View entryView = inflater.inflate(R.layout.item_import, root, false);
            return new ContentViewHolder(entryView);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (getItemViewType(position) == VIEW_TYPE_HEADER) {
            HeaderViewHolder header = (HeaderViewHolder) holder;
            header.itemView.setOnClickListener(view -> {
                if (headerCallback != null) {
                    headerCallback.onHeaderClick();
                }
            });
        } else {
            ContentViewHolder contentHolder = (ContentViewHolder) holder;
            ImageTraceEntry entry = traceList.get(position - 1);
            contentHolder.populate(entry);
        }
    }

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

    public void updateList(List<ImageTraceEntry> newList) {
        this.traceList = newList;
        notifyDataSetChanged();
    }

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

    class ContentViewHolder extends RecyclerView.ViewHolder {
        ImageView imagePreviewView;
        ImageView favoriteToggleView;

        public ContentViewHolder(@NonNull View itemView) {
            super(itemView);
            imagePreviewView = itemView.findViewById(R.id.image_view);
            favoriteToggleView = itemView.findViewById(R.id.btn_favorite);
        }

        void populate(ImageTraceEntry entryData) {
            String filePath = entryData.getPath();

            Glide.with(contextActivity)
                    .load(filePath)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .transform(new CenterCrop(), new RoundedCorners(32))
                    .placeholder(R.mipmap.placeholder)
                    .error(R.mipmap.placeholder)
                    .into(imagePreviewView);

            favoriteToggleView.setImageResource(entryData.isFavorite() ? R.drawable.like : R.drawable.dislike);

            favoriteToggleView.setOnClickListener(click -> {
                boolean newStatus = !entryData.isFavorite();
                entryData.setFavorite(newStatus);

                Executors.newSingleThreadExecutor().execute(() -> {
                    AppDatabase.getInstance(contextActivity).imageTraceEntryDao().update(entryData);
                });

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

            imagePreviewView.setOnClickListener(click -> {
                Intent previewIntent = new Intent(contextActivity, ImageTraceActivity.class);
                previewIntent.putExtra("imagePath", entryData.getPath());
                contextActivity.startActivity(previewIntent);
            });
        }
    }
}