package com.ardraw.ardrawingflow.ui.activity;

import android.os.Bundle;
import android.util.Log;

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.ardraw.ardrawingflow.R;
import com.ardraw.ardrawingflow.data.database.entity.FlowData;
import com.ardraw.ardrawingflow.databinding.ActivitySecondBinding;
import com.ardraw.ardrawingflow.ui.adapter.FlowItemAdapter;
import com.ardraw.ardrawingflow.ui.viewmodel.FlowViewModel;
import com.ardraw.ardrawingflow.util.ItemDecoration;

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

public class SecondActivity extends AppCompatActivity {
    private ActivitySecondBinding binding;
    private FlowItemAdapter adapter;
    private FlowViewModel flowViewModel;
    private String title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivitySecondBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        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() {
        String path = getIntent().getStringExtra("path");
        if (path == null) {
            finish();
            return;
        }

        String[] parts = path.split("/");
        title = parts[0].split("_")[1];

        flowViewModel = new ViewModelProvider(this).get(FlowViewModel.class);

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

        ItemDecoration itemDecoration = new ItemDecoration(35, 15, 20);
        binding.recyclerView.addItemDecoration(itemDecoration);
    }

    private void initEvent() {
        binding.back.setOnClickListener(v -> {
            finish();
        });
        binding.text.setText(title);
        loadImage();
    }

    private void loadImage() {
        flowViewModel
                .getDataByName(title)
                .observe(this, new Observer<List<FlowData>>() {
                    @Override
                    public void onChanged(List<FlowData> flowData) {
                        adapter.refreshItems(flowData);
                    }
                });
    }

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