package com.draw.painting.canvas.presentation;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.SnapHelper;

import com.draw.painting.canvas.CanvasApp;
import com.draw.painting.canvas.R;
import com.draw.painting.canvas.adapters.SketchCategoryAdapter;
import com.draw.painting.canvas.adapters.FeaturedSketchAdapter;
import com.draw.painting.canvas.databinding.FragmentExploreBinding;
import com.draw.painting.canvas.core.SketchRepository;
import com.draw.painting.canvas.onClickListener;

import java.io.InputStream;

public class ExploreFragment extends Fragment implements onClickListener {

    private FragmentExploreBinding binding;
    private ActivityResultLauncher<Intent> galleryLauncher;

    public ExploreFragment() {

    }

    public static ExploreFragment newInstance() {
        ExploreFragment fragment = new ExploreFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

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

        // 初始化相册选择器
        galleryLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
                        Uri imageUri = result.getData().getData();
                        if (imageUri != null) {
                            // 验证图片是否合规
                            if (validateImage(imageUri)) {
                                // 图片合规，打开相机界面并传递自定义图片
                                Intent intent = new Intent(requireContext(), ARCameraActivity.class);
                                intent.putExtra("custom_image_uri", imageUri.toString());
                                startActivity(intent);
                            }
                            // 如果验证失败，validateImage 方法内已显示 Toast，此处无需处理
                        } else {
                            Toast.makeText(requireContext(), getString(R.string.permission_fail), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentExploreBinding.inflate(getLayoutInflater());
        onInitViews();
        onInitFeaturedRecycler();
        onInitCategoryRecycler();
        return binding.getRoot();
    }

    private void onInitViews() {
        // 设置相册导入按钮点击事件
        binding.btnImportGallery.setOnClickListener(v -> openGallery());
    }

    /**
     * 初始化推荐区（横向滑动）
     */
    private void onInitFeaturedRecycler() {
        FeaturedSketchAdapter featuredAdapter = new FeaturedSketchAdapter(requireContext(), SketchRepository.getFeaturedSketches());
        featuredAdapter.setListener(this::onClickItem);
        
        LinearLayoutManager layoutcore = new LinearLayoutManager(requireContext());
        layoutcore.setOrientation(LinearLayoutManager.HORIZONTAL);
        
        binding.recyclerFeatured.setAdapter(featuredAdapter);
        binding.recyclerFeatured.setLayoutManager(layoutcore);
        
        // 添加滚动吸附效果（让卡片居中对齐）
        SnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(binding.recyclerFeatured);
    }

    /**
     * 初始化分类列表
     */
    private void onInitCategoryRecycler() {
        SketchCategoryAdapter categoryAdapter = new SketchCategoryAdapter(requireContext(), SketchRepository.getAllDir());
        categoryAdapter.setListener(this::onClickItem);
        
        LinearLayoutManager layoutcore = new LinearLayoutManager(requireContext());
        
        binding.recyclerCategories.setAdapter(categoryAdapter);
        binding.recyclerCategories.setLayoutManager(layoutcore);
    }

    /**
     * 打开相册选择图片
     */
    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        galleryLauncher.launch(intent);
    }

    /**
     * 验证图片是否合规
     * @param uri 图片 URI
     * @return true 表示合规，false 表示不合规
     */
    private boolean validateImage(Uri uri) {
        try {
            // 1. 检查文件大小（限制为 4MB）
            long fileSize = getFileSize(uri);
            if (fileSize > 4 * 1024 * 1024) {
                Toast.makeText(requireContext(), getString(R.string.file_fail), Toast.LENGTH_LONG).show();
                return false;
            }

            // 2. 检查图片是否有效
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            InputStream inputStream = requireContext().getContentResolver().openInputStream(uri);
            BitmapFactory.decodeStream(inputStream, null, options);
            if (inputStream != null) {
                inputStream.close();
            }

            int width = options.outWidth;
            int height = options.outHeight;

            if (width <= 0 || height <= 0) {
                Toast.makeText(requireContext(), getString(R.string.file_invalid), Toast.LENGTH_SHORT).show();
                return false;
            }

            // 3. 检查图片格式
            String mimeType = options.outMimeType;
            if (mimeType == null || (!mimeType.equals("image/jpeg") && 
                !mimeType.equals("image/png") && !mimeType.equals("image/jpg"))) {
                Toast.makeText(requireContext(), getString(R.string.file_format_unsupported), Toast.LENGTH_SHORT).show();
                return false;
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(requireContext(), getString(R.string.file_read_error), Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    /**
     * 获取文件大小
     * @param uri 文件 URI
     * @return 文件大小（字节）
     */
    private long getFileSize(Uri uri) {
        long size = 0;
        try {
            Cursor cursor = requireContext().getContentResolver().query(
                    uri, null, null, null, null);
            if (cursor != null) {
                int sizeIndex = cursor.getColumnIndex(MediaStore.Images.Media.SIZE);
                if (sizeIndex != -1 && cursor.moveToFirst()) {
                    size = cursor.getLong(sizeIndex);
                }
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    @Override
    public void onClickItem(boolean viewAll, String dir) {
        Intent intent;
        if (viewAll) {
            // 查看分类下的所有图片
            intent = new Intent(requireContext(), CategoryDetailActivity.class);
            intent.putExtra(CanvasApp.Key_ViewDir, dir);
        } else {
            // 直接进入AR绘画模式
            intent = new Intent(requireContext(), ARCameraActivity.class);
            intent.putExtra(CanvasApp.Key_Camera, dir);
        }
        startActivity(intent);
    }
}