package com.prank.funnypranksounds.ui.activity;

import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import com.prank.funnypranksounds.R;
import com.prank.funnypranksounds.data.local.entity.AudioData;
import com.prank.funnypranksounds.databinding.ActivityCategoryBinding;
import com.prank.funnypranksounds.ui.adapter.AudioAdapter;
import com.prank.funnypranksounds.utils.ItemDecoration;
import com.prank.funnypranksounds.viewmodel.AudioViewModel;

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

public class CategoryActivity extends AppCompatActivity {

    private ActivityCategoryBinding binding;
    private AudioViewModel audioViewModel;
    private AudioAdapter adapter;
    private String name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityCategoryBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        EdgeToEdge.enable(this);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        initData();
        initEvent();

    }

    private void initData() {

        name = getIntent().getStringExtra("name");
        if (name == null) {
            finish();
            return;
        }

        audioViewModel = new ViewModelProvider(this,
                new ViewModelProvider.AndroidViewModelFactory(getApplication()))
                .get(AudioViewModel.class);

        binding.recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        adapter = new AudioAdapter(new ArrayList<>(), audioViewModel, this, this, 1);
        binding.recyclerView.setAdapter(adapter);

        ItemDecoration itemDecoration = new ItemDecoration(16, 19, 10);
        binding.recyclerView.addItemDecoration(itemDecoration);

    }

    private void initEvent() {

        binding.title.setText(name);
        binding.back.setOnClickListener(v -> finish());
        loadCategory();

    }

    private void loadCategory() {
        audioViewModel
                .getCategory(name)
                .observe(this, new Observer<List<AudioData>>() {
                    @Override
                    public void onChanged(List<AudioData> audioDataList) {
                        adapter.updateData(audioDataList);
                    }
                });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }
}