package com.ardraw.ardrawingflow.ui.adapter;

import android.content.Context;
import android.content.Intent;
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.RecyclerView;

import com.ardraw.ardrawingflow.R;
import com.ardraw.ardrawingflow.callback.DeleteCallback;
import com.ardraw.ardrawingflow.data.database.AppDatabase;
import com.ardraw.ardrawingflow.data.database.entity.FlowData;
import com.ardraw.ardrawingflow.ui.activity.DetailActivity;
import com.ardraw.ardrawingflow.ui.activity.SecondActivity;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;

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

public class FlowItemAdapter extends RecyclerView.Adapter<FlowItemAdapter.ItemViewHolder> {
    private List<FlowData> dataItems;
    private final Context appContext;
    private final int displayMode;
    private DeleteCallback deleteCallback;

    public FlowItemAdapter(Context appContext, List<FlowData> dataItems, int displayMode) {
        this.appContext = appContext;
        this.dataItems = dataItems;
        this.displayMode = displayMode;
    }

    public void refreshItems(List<FlowData> updatedItems) {
        this.dataItems = updatedItems;
        notifyDataSetChanged();
    }

    public void setDeleteCallback(DeleteCallback deleteCallback) {
        this.deleteCallback = deleteCallback;
    }

    @NonNull
    @Override
    public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(appContext);
        View itemView = inflater.inflate(R.layout.item_flow, parent, false);
        return new ItemViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {
        FlowData currentItem = dataItems.get(position);
        String displayName = extractName(currentItem);
        holder.renderItem(currentItem, displayName, displayMode);
    }

    private String extractName(FlowData item) {
        if (displayMode == 0) {
            String path = item.getImagePath();
            String[] segments = path.split("/");
            return segments[0].split("_")[1];
        }
        return "";
    }

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

    public class ItemViewHolder extends RecyclerView.ViewHolder {
        private final ImageView previewImage;
        private final ImageView favoriteIcon;
        private final ImageView deleteIcon;
        private final TextView titleText;

        public ItemViewHolder(@NonNull View view) {
            super(view);
            previewImage = view.findViewById(R.id.item_image);
            favoriteIcon = view.findViewById(R.id.like);
            deleteIcon = view.findViewById(R.id.delete);
            titleText = view.findViewById(R.id.title);
        }

        void renderItem(FlowData item, String displayName, int mode) {
            configureDisplay(displayName, mode);
            loadImageContent(item.getImagePath());
            setFavoriteState(item);
            attachListeners(item, mode);
        }

        private void configureDisplay(String name, int mode) {
            if (mode == 0) {
                titleText.setText(name);
                titleText.setVisibility(View.VISIBLE);
                favoriteIcon.setVisibility(View.GONE);
            } else if (mode == 1) {
                deleteIcon.setVisibility(View.VISIBLE);
            }
        }

        private void loadImageContent(String path) {
            String formattedPath = adjustImagePath(path);
            Glide.with(appContext)
                    .load(formattedPath)
                    .placeholder(R.mipmap.placeholder)
                    .apply(RequestOptions.bitmapTransform(new RoundedCorners(32)))
                    .into(previewImage);
        }

        private String adjustImagePath(String path) {
            return path.startsWith("/data/user/") ? path : "file:///android_asset/" + path;
        }

        private void setFavoriteState(FlowData item) {
            int icon = item.isLike() ? R.drawable.like : R.drawable.dislike;
            favoriteIcon.setImageResource(icon);
        }

        private void attachListeners(FlowData item, int mode) {
            previewImage.setOnClickListener(view -> handleImageTap(item, mode));
            favoriteIcon.setOnClickListener(view -> switchFavorite(item));
            deleteIcon.setOnClickListener(view ->{
                int position = getAdapterPosition();
                if (position != RecyclerView.NO_POSITION && deleteCallback != null) {
                    deleteCallback.onDelete(dataItems.get(position));
                }
            });
        }

        private void handleImageTap(FlowData item, int mode) {
            Intent navigationIntent = createNavigationIntent(item, mode);
            appContext.startActivity(navigationIntent);
        }

        private Intent createNavigationIntent(FlowData item, int mode) {
            Class<?> targetActivity = mode == 0 ? SecondActivity.class : DetailActivity.class;
            return new Intent(appContext, targetActivity)
                    .putExtra("path", item.getImagePath());
        }

        private void switchFavorite(FlowData item) {
            item.setLike(!item.isLike());
            persistItemUpdate(item);
            notifyItemChanged(getAdapterPosition());
        }

        private void persistItemUpdate(FlowData item) {
            ExecutorService executor = Executors.newSingleThreadExecutor();
            executor.submit(() -> {
                AppDatabase db = AppDatabase.getInstance(appContext);
                db.flowDataDao().update(item);
            });
        }
    }
}