package com.ar.artracestudio.fragment;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;

import com.ar.artracestudio.MyApplication;
import com.ar.artracestudio.R;
import com.ar.artracestudio.adapter.CategoryAdapter;
import com.ar.artracestudio.databinding.FragmentCategoryBinding;
import com.ar.artracestudio.room.AppDatabase;
import com.ar.artracestudio.room.ImageEntry;
import com.ar.artracestudio.utils.DatabaseUtils;
import com.ar.artracestudio.utils.ItemDecoration;
import com.ar.artracestudio.utils.Names;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class CategoryFragment extends Fragment {

    private FragmentCategoryBinding binding;
    private String format;
    private final List<String> originalCategories = Names.getAllDir();
    private List<String> displayCategories = new ArrayList<>();
    private List<ImageEntry> images = new ArrayList<>();
    private CategoryAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        binding = FragmentCategoryBinding.inflate(inflater, container, false);


        initData();
        initEvent();
        setupRecyclerView();

        loadImages(originalCategories);

        return binding.getRoot();
    }

    private void initData() {

        for (String category : originalCategories) {
            displayCategories.add(category.substring(4)); // 去掉前缀 "png_"
            Log.d("---", "displayCategories:  " + displayCategories);
        }

    }


    private void initEvent() {
        binding.setting.setOnClickListener(v -> showCustomBottomSheetDialog());
    }

    private void setupRecyclerView() {

        binding.recyclerview.setLayoutManager(new GridLayoutManager(getContext(), 2));

        adapter = new CategoryAdapter(requireActivity(), new ArrayList<>(), originalCategories, displayCategories);
        Log.d("---", "image" + images);
        binding.recyclerview.setAdapter(adapter);

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

    private void loadImages(List<String> originalList) {
        // 用于合并所有查询结果的列表
        Map<Integer, List<ImageEntry>> queryResultsMap = new HashMap<>();
        int totalQueries = originalList.size();

        for (int i = 0; i < totalQueries; i++) {
            String original = originalList.get(i);
            int finalI = i;
            AppDatabase.getInstance(requireContext())
                    .imageEntryDao()
                    .getFirstImagesByCategoryLive(original)
                    .observe(getViewLifecycleOwner(), new Observer<List<ImageEntry>>() {
                        @Override
                        public void onChanged(List<ImageEntry> imageEntries) {
                            queryResultsMap.put(finalI, imageEntries);
                            if (queryResultsMap.size() == totalQueries) {
                                // 所有查询结果都已返回，按照索引顺序合并数据并更新适配器
                                List<ImageEntry> allImageEntries = new CopyOnWriteArrayList<>();
                                for (int j = 0; j < totalQueries; j++) {
                                    List<ImageEntry> currentEntries = queryResultsMap.get(j);
                                    if (currentEntries!= null) {
                                        allImageEntries.addAll(currentEntries);
                                    }
                                }
                                adapter.updateData(allImageEntries);
                            }
                        }
                    });
        }
    }

    private void showCustomBottomSheetDialog() {
        BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(requireContext());
        View dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.setting_dialog, null);
        // 禁止点击其他页面取消
        bottomSheetDialog.setCanceledOnTouchOutside(false);

        TextView version = dialogView.findViewById(R.id.version_number);

        try {
            PackageInfo packageInfo = MyApplication.getContext().getPackageManager().getPackageInfo(MyApplication.getContext().getPackageName(), 0);
            String versionName = packageInfo.versionName;
            format = String.format(getString(R.string.gp), packageInfo.packageName);
            version.setText(versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            version.setText("1.0.0");
            format = String.format(getString(R.string.gp), "com.ar.artracestudio");
        }


//        dialogView.findViewById(R.id.privacy).setOnClickListener(v -> {
//            // 处理选项 1
//            Intent intent = new Intent(requireActivity(), PrivacyActivity.class);
//            startActivity(intent);
//            // 销毁 BottomSheetDialog 对象
//            bottomSheetDialog.dismiss();
//        });

        dialogView.findViewById(R.id.share).setOnClickListener(v -> {

            shareString(format);
            // 处理选项 2
            bottomSheetDialog.dismiss();
        });

        dialogView.findViewById(R.id.version).setOnClickListener(v -> {

        });

        dialogView.findViewById(R.id.cancel_button).setOnClickListener(v -> {

            bottomSheetDialog.dismiss();
        });

        bottomSheetDialog.setContentView(dialogView);
        bottomSheetDialog.show();
    }

    public void shareString(String content) {
        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_TEXT, content);//分享的文本内容
        sendIntent.setType("text/plain");
        startActivity(Intent.createChooser(sendIntent, "Share to"));
    }

}