package com.example.gallery.adapters;

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.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

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

import com.bumptech.glide.Glide;
import com.example.gallery.MainActivity;
import com.example.gallery.R;
import com.example.gallery.VideoPlayerActivity;
import com.example.gallery.api.ApiClient;
import com.example.gallery.api.ApiService;
import com.example.gallery.models.Publication;
import com.example.gallery.models.RatingRequest;
import com.example.gallery.models.RatingResponse;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PostsAdapter extends RecyclerView.Adapter<PostsAdapter.PostViewHolder> {

    private final Context context;
    private final ApiService apiService;
    private final boolean isLoggedIn;

    private final List<Publication> allPosts = new ArrayList<>();
    private final List<Publication> visiblePosts = new ArrayList<>();

    private Boolean pinnedFilter = null;
    private String contentTypeFilter = null;
    private SortMode sortMode = SortMode.TIME;

    public enum SortMode { TIME, RATING }

    public PostsAdapter(Context context, List<Publication> posts, boolean isLoggedIn) {
        this.context = context;
        this.isLoggedIn = isLoggedIn;
        this.apiService = ApiClient.getClient().create(ApiService.class);
        setPosts(posts);
    }

    public void setPosts(List<Publication> posts) {
        allPosts.clear();
        if (posts != null) allPosts.addAll(posts);
        applyFilters();
    }

    public void filterPinned(Boolean pinned) {
        pinnedFilter = pinned;
        applyFilters();
    }

    public void filterContentType(String type) {
        contentTypeFilter = type;
        applyFilters();
    }

    public void sortBy(SortMode mode) {
        sortMode = mode;
        applyFilters();
    }

    private void applyFilters() {
        visiblePosts.clear();

        for (Publication p : allPosts) {
            if (pinnedFilter != null && p.is_pinned != pinnedFilter) continue;
            if (contentTypeFilter != null &&
                    !contentTypeFilter.equalsIgnoreCase(p.content_type)) continue;
            visiblePosts.add(p);
        }

        if (sortMode == SortMode.TIME) {
            Collections.sort(visiblePosts,
                    (a, b) -> b.time_created.compareTo(a.time_created));
        } else {
            Collections.sort(visiblePosts,
                    (a, b) -> Float.compare(b.average_score, a.average_score));
        }

        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context)
                .inflate(R.layout.item_post, parent, false);
        return new PostViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull PostViewHolder holder, int position) {

        Publication post = visiblePosts.get(position);

        // ---------- USER SCORE ----------
        int userScore = post.current_user_score != null ? post.current_user_score : 0;
        holder.userRatingBar.setOnRatingBarChangeListener(null);
        holder.userRatingBar.setRating(userScore);
        holder.yourRating.setText(String.valueOf(userScore));

        // ---------- TEXT ----------
        holder.postDescription.setText(post.description == null ? "" : post.description);
        holder.postUserName.setText(post.user_detail == null ? "User" : post.getUsername());
        holder.mediaTypeBadge.setText(
                post.content_type == null ? "MEDIA" : post.content_type.toUpperCase());


        // ---------- MEDIA ----------
        if ("video".equalsIgnoreCase(post.content_type)) {
            // Load video thumbnail
            Glide.with(context).asBitmap().load(post.video).into(holder.postImage);

            // Make the thumbnail clickable to play video
            holder.postImage.setOnClickListener(v -> {
                Intent i = new Intent(context, VideoPlayerActivity.class);
                i.putExtra("videoUrl", post.video);
                context.startActivity(i);
            });

        } else {
            // Load image for normal posts
            Glide.with(context).load(post.image).into(holder.postImage);
        }




        // ---------- AVERAGE ----------
        holder.txtAverageValue.setText(String.format("%.1f", post.average_score));
        holder.averageRatingBar.setRating(post.average_score);

        if (!isLoggedIn) {
            holder.userRatingBar.setIsIndicator(true);
            return;
        }

        holder.userRatingBar.setIsIndicator(false);

        holder.userRatingBar.setOnRatingBarChangeListener((bar, rating, fromUser) -> {
            if (!fromUser) return;

            int score = Math.round(rating);
            int adapterPosition = holder.getAdapterPosition();
            if (adapterPosition == RecyclerView.NO_POSITION) return;

            Publication current = visiblePosts.get(adapterPosition);

            String token = context.getSharedPreferences("MyAppPrefs", Context.MODE_PRIVATE)
                    .getString("authToken", null);

            apiService.ratePublication("Token " + token,
                            new RatingRequest(current.pk, score))
                    .enqueue(new Callback<RatingResponse>() {
                        @Override
                        public void onResponse(@NonNull Call<RatingResponse> call,
                                               @NonNull Response<RatingResponse> response) {

                            if (!response.isSuccessful() || response.body() == null) return;

                            RatingResponse body = response.body();

                            current.current_user_score = score;


                            if (body.average_score != null) {
                                current.average_score = body.average_score;
                            }

                            for (Publication p : allPosts) {
                                if (p.pk == current.pk) {
                                    p.current_user_score = current.current_user_score;
                                    p.average_score = current.average_score;
                                    break;
                                }
                            }

                            holder.yourRating.setText(String.valueOf(current.current_user_score));
                            holder.averageRatingBar.setRating(current.average_score);
                            holder.txtAverageValue.setText(
                                    String.format("%.1f", current.average_score)
                            );

                            if (context instanceof MainActivity) {
                                ((MainActivity) context).runOnUiThread(() -> {
                                    ((MainActivity) context).loadPublications();
                                });
                            }
                        }

                        @Override
                        public void onFailure(@NonNull Call<RatingResponse> call,
                                              @NonNull Throwable t) {
                            Toast.makeText(context,
                                    "Network error", Toast.LENGTH_SHORT).show();
                        }
                    });
        });
    }

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

    static class PostViewHolder extends RecyclerView.ViewHolder {

        RatingBar averageRatingBar, userRatingBar;
        TextView txtAverageValue, yourRating, postDescription, postUserName, mediaTypeBadge;
        ImageView postImage;

        PostViewHolder(View itemView) {
            super(itemView);

            averageRatingBar = itemView.findViewById(R.id.averageRatingBar);
            userRatingBar = itemView.findViewById(R.id.userRatingBar);
            txtAverageValue = itemView.findViewById(R.id.averageRatingText);
            yourRating = itemView.findViewById(R.id.yourRating);
            postDescription = itemView.findViewById(R.id.postDescription);
            postUserName = itemView.findViewById(R.id.postUserName);
            mediaTypeBadge = itemView.findViewById(R.id.mediaTypeBadge);
            postImage = itemView.findViewById(R.id.postImage);



        }
    }
}
