package com.lock.arcanvasart.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.lock.arcanvasart.R;
import com.lock.arcanvasart.Utils.ItemDecoration;
import com.lock.arcanvasart.Utils.Names;
import com.lock.arcanvasart.adapter.CategoryAdapter;
import com.lock.arcanvasart.databinding.FragmentCategoryBinding;
import com.lock.arcanvasart.room.AppDatabase;
import com.lock.arcanvasart.room.FavoriteImage;

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

public class CategoryFragment extends Fragment {

    private FragmentCategoryBinding binding;
    private CategoryAdapter imageAdapter;
    private List<FavoriteImage> images = new ArrayList<>();
    private boolean isSingleColumn = true; // 默认单列布局
    private AppDatabase appDatabase;
    private LiveData<List<FavoriteImage>> favoriteImagesLiveData;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentCategoryBinding.inflate(inflater, container, false);

        // 初始化 AppDatabase 和 LiveData
        appDatabase = AppDatabase.getInstance(getContext());

        // 初始化下拉框（Spinner）
        setupSpinner();

        // 初始化 RecyclerView
        setupRecyclerView();

        // 初始化列切换按钮
        setupColumnToggleButtons();

        return binding.getRoot();
    }

    private void setupSpinner() {
        // 获取所有类别的原始列表
        List<String> originalCategories = Names.getAllDir();
        List<String> displayCategories = new ArrayList<>(); // 用于显示的类别名称列表（去掉前缀）

        // 遍历原始类别，去掉每个类别的 "png_" 前缀
        for (String category : originalCategories) {
            if (category.startsWith("png_")) {
                displayCategories.add(category.substring(4)); // 去掉前缀 "png_"
            } else {
                displayCategories.add(category);
            }
        }

        // 使用处理后的类别列表创建 ArrayAdapter
        ArrayAdapter<String> adapter = new ArrayAdapter<>(requireContext(), android.R.layout.simple_spinner_item, displayCategories);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        binding.categorySpinner.setAdapter(adapter);

        // 设置 Spinner 的选择监听器
        binding.categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // 根据选择的类别加载图片（使用原始类别名称）
                String selectedCategory = originalCategories.get(position);
                loadImages(selectedCategory); // 加载选中类别的图片
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 如果没有选中任何项，则不做任何操作
            }
        });
    }

    private void setupRecyclerView() {
        // 初始化适配器并设置 RecyclerView 的布局管理器
        imageAdapter = new CategoryAdapter(getContext(), images);
        binding.recyclerview.setLayoutManager(new LinearLayoutManager(getContext())); // 默认使用单列布局
        binding.recyclerview.setAdapter(imageAdapter);

        // 添加自定义的 ItemDecoration 用于设置 item 间距
        ItemDecoration itemDecoration = new ItemDecoration(12, 10, 9);
        binding.recyclerview.addItemDecoration(itemDecoration);
    }

    private void setupColumnToggleButtons() {
        // 设置列切换按钮的默认状态
        binding.btnSingleColumn.setImageResource(R.drawable.single);
        binding.btnDoubleColumn.setImageResource(R.drawable.un_double);

        // 设置单列按钮的点击事件
        binding.btnSingleColumn.setOnClickListener(v -> {
            if (!isSingleColumn) {
                // 切换为单列布局
                binding.recyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
                binding.btnSingleColumn.setImageResource(R.drawable.single);
                binding.btnDoubleColumn.setImageResource(R.drawable.un_double);
                isSingleColumn = true; // 更新状态
            }
        });

        // 设置双列按钮的点击事件
        binding.btnDoubleColumn.setOnClickListener(v -> {
            if (isSingleColumn) {
                // 切换为双列布局
                binding.recyclerview.setLayoutManager(new GridLayoutManager(getContext(), 2));
                binding.btnSingleColumn.setImageResource(R.drawable.un_single);
                binding.btnDoubleColumn.setImageResource(R.drawable.double_row);
                isSingleColumn = false; // 更新状态
            }
        });
    }

    private void loadImages(String category) {
        // 获取指定类别的图片，并将其包装成 LiveData 进行观察
        favoriteImagesLiveData = appDatabase.favoriteImageDao().getImagesByCategory(category);

        // 观察 LiveData 数据变化
        favoriteImagesLiveData.observe(getViewLifecycleOwner(), favoriteImages -> {
            images.clear(); // 清空现有的图片列表
            images.addAll(favoriteImages); // 添加新的图片数据
            imageAdapter.notifyDataSetChanged(); // 更新 RecyclerView
        });
    }
}
