package com.wall.engine.wallpaper;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsControllerCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ad.tradpluslibrary.TPAdManager;

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

import kotlin.Unit;
import kotlin.jvm.functions.Function0;

public class FavoriteActivity extends AppCompatActivity {

    private RecyclerView rvFavoriteImages;
    private TextView tvEmpty;
    private D4ImageAdapter adapter;
    private FavoriteManager favoriteManager;
    private List<WallpaperItem> favoriteList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_favorite);

        setupStatusBar();
        initViews();
        setupRecyclerView();
        loadFavoriteData();
        TPAdManager.INSTANCE.showTPAD(FavoriteActivity.this, new Function0<Unit>() {
            @Override
            public Unit invoke() {
                return null;
            }
        });
    }

    private void setupStatusBar() {
        Window window = getWindow();
        WindowCompat.setDecorFitsSystemWindows(window, false);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(getResources().getColor(android.R.color.transparent));

        WindowInsetsControllerCompat insetsController = WindowCompat.getInsetsController(window, window.getDecorView());
        if (insetsController != null) {
            insetsController.setAppearanceLightStatusBars(true);
        }

        View statusBarPlaceholder = findViewById(R.id.status_bar_placeholder);
        int statusBarHeight = getStatusBarHeight();
        if (statusBarHeight > 0) {
            ViewGroup.LayoutParams params = statusBarPlaceholder.getLayoutParams();
            params.height = statusBarHeight;
            statusBarPlaceholder.setLayoutParams(params);
        }
    }

    private int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    private void initViews() {
        rvFavoriteImages = findViewById(R.id.rv_favorite_images);
        tvEmpty = findViewById(R.id.tv_empty);

        findViewById(R.id.btn_back).setOnClickListener(v -> finish());

        favoriteManager = new FavoriteManager(this);
        favoriteList = new ArrayList<>();
    }

    private void setupRecyclerView() {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        rvFavoriteImages.setLayoutManager(gridLayoutManager);

        adapter = new D4ImageAdapter(this, favoriteList);
        rvFavoriteImages.setAdapter(adapter);

        adapter.setOnItemClickListener((position, wallpaperItem) -> {
            if (wallpaperItem == null) {
                Toast.makeText(FavoriteActivity.this, "Data error", Toast.LENGTH_SHORT).show();
                return;
            }

            String highResImageUrl = wallpaperItem.getUrls().getRegular();
            if (highResImageUrl == null || highResImageUrl.isEmpty()) {
                highResImageUrl = wallpaperItem.getUrls().getFull();
            }

            if (highResImageUrl == null || highResImageUrl.isEmpty()) {
                Toast.makeText(FavoriteActivity.this, "Image URL is empty", Toast.LENGTH_SHORT).show();
                return;
            }

            Intent intent = new Intent(FavoriteActivity.this, FullImageActivity.class);
            intent.putExtra(FullImageActivity.EXTRA_IMAGE_URL, highResImageUrl);
            intent.putExtra(FullImageActivity.EXTRA_IMAGE_ID, wallpaperItem.getId());

            String description = wallpaperItem.getAlt_description();
            if (description == null || description.isEmpty()) {
                description = "Favorited wallpapers";
            }
            intent.putExtra(FullImageActivity.EXTRA_IMAGE_DESC, description);

            startActivity(intent);
        });
    }

    private void loadFavoriteData() {
        favoriteList.clear();
        favoriteList.addAll(favoriteManager.getFavoriteItems());

        Log.d("FavoriteActivity", "加载收藏数据，数量: " + favoriteList.size());

        if (favoriteList.isEmpty()) {
            tvEmpty.setVisibility(View.VISIBLE);
            rvFavoriteImages.setVisibility(View.GONE);

        } else {
            tvEmpty.setVisibility(View.GONE);
            rvFavoriteImages.setVisibility(View.VISIBLE);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadFavoriteData();
    }
}