package com.paint.sweet.drawing.sweetactivity;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.PointF;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.ad.toponlibrary.AdManager;
import com.google.common.util.concurrent.ListenableFuture;
import com.paint.sweet.drawing.PaintingApp;
import com.paint.sweet.drawing.R;
import com.paint.sweet.drawing.sweetmanager.AppUtils;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

public class PhotoSelectActivity extends AppCompatActivity implements View.OnTouchListener, View.OnClickListener {

    private CameraSelector cameraSelector;
    private String[] permissions;
    private int range;
    private Camera camera;
    private ImageCapture imageCapture;
    private PreviewView previewView;
    private ImageView imageView;
    private SeekBar seekBar;

    private Double d;

    private int MODE;//当前状态
    public static final int MODE_NONE = 0;//无操作
    public static final int MODE_DRAG = 1;//单指操作
    public static final int MODE_SCALE = 2;//双指操作

    private Matrix startMatrix;
    private Matrix endMatrix = new Matrix();//变化后的矩阵
    private PointF startPointF = new PointF();//初始坐标
    private float distance;//初始距离
    private float scaleMultiple;//缩放倍数

    private ImageView flashIm, imZoom, imBack, imLock; // 新增：锁定按钮
    private ImageView imPhoto;

    private String curBitmapPath;
    private boolean hasPermission = false;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;

    // 新增：锁定状态标记 - 默认未锁定
    private boolean isImageLocked = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTransparentStatusBarAndFullScreenContent();
        setContentView(R.layout.activity_photo_select);
        AdManager.loadAllAd();
        AdManager.showTopOn(this, () -> {});
        previewView = findViewById(R.id.preview);
        imageView = findViewById(R.id.image);
        imBack = findViewById(R.id.back);

        seekBar = findViewById(R.id.seekbar);
        flashIm = findViewById(R.id.im_flash);
        imPhoto = findViewById(R.id.im_photo);
        imZoom = findViewById(R.id.im_zoom);
        imLock = findViewById(R.id.im_lock); // 新增：绑定锁定按钮

        curBitmapPath = getIntent().getStringExtra(PaintingApp.Key_Camera);

        // 注册相册选择回调，增加图片大小和类型校验
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
                Uri imageUri = result.getData().getData();
                if (imageUri == null) {
                    // 图片URI为空
                    Toast.makeText(PhotoSelectActivity.this, "Failed to upload", Toast.LENGTH_SHORT).show();
                    Log.d("---------------tt", "----imageUri-111-null");
                    return;
                }

                // 校验文件大小（不超过4M）
                double uriFileSize = getUriFileSize(PhotoSelectActivity.this, imageUri);
                if (uriFileSize >= 4) {
                    // 超过4M：Toast提示
                    Toast.makeText(PhotoSelectActivity.this, "Please ensure the file is no larger than 4M", Toast.LENGTH_SHORT).show();
                    Log.d("---------------tt", "----imageUri-222-uriFileSize=" + uriFileSize);
                    return;
                }

                // 校验通过：设置图片
                Log.d("---------------tt", "----imageUri-333-uriFileSize=" + uriFileSize);
                imageView.setImageURI(imageUri);
            }
        });

        init();
        initClick();
    }

    // ========== 补充方法实现 ==========
    private void setTransparentStatusBarAndFullScreenContent() {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            );
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        }
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
    // ========== 方法实现结束 ==========

    private void onInitIm(float imW, float imH) {
        Point screen = AppUtils.getScreen(this);
        float newX = screen.x / 2f - imW / 2;
        float newY = screen.y / 2f - imH / 2;
        startMatrix = new Matrix();
        startMatrix.postTranslate(newX, newY);
        imageView.setImageMatrix(startMatrix);

        Log.d("---------------tt", "------startMatrix-----x=" + newX + "------y=" + newY);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // 新增：如果锁定状态为true，直接返回false，不处理触摸事件
        if (isImageLocked) {
            return false;
        }

        switch (event.getAction() & event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                startMatrix.set(imageView.getImageMatrix());
                endMatrix.set(imageView.getImageMatrix());
                startPointF.set(event.getX(), event.getY());
                Log.d("---------------tt", "------ACTION_DOWN-----x=" + event.getX() + "------y=" + event.getY());
                MODE = MODE_DRAG;
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                startMatrix.set(endMatrix);
                distance = AppUtils.getDistance(event);
                MODE = MODE_SCALE;
                break;
            case MotionEvent.ACTION_MOVE://滑动（单+双）
                if (MODE == MODE_DRAG) {//单指滑动时
                    endMatrix.set(startMatrix);
                    //向矩阵传入位移距离
                    endMatrix.postTranslate(event.getX() - startPointF.x, event.getY() - startPointF.y);
                    Log.d("---------------tt", "------ACTION_MOVE-----x=" + event.getX() + "------y=" + event.getY());
                } else if (MODE == MODE_SCALE) {//双指滑动时
                    //计算缩放倍数
                    scaleMultiple = AppUtils.getDistance(event) / distance;
                    //获取初始矩阵
                    endMatrix.set(startMatrix);
                    //向矩阵传入缩放倍数
                    endMatrix.postScale(scaleMultiple, scaleMultiple, startPointF.x, startPointF.y);
                }
                break;
            case MotionEvent.ACTION_UP://单指离开
            case MotionEvent.ACTION_POINTER_UP://双指离开
                //手指离开后，重置状态
                MODE = MODE_NONE;
                break;
        }
        //事件结束后，把矩阵的变化同步到ImageView上
        imageView.setImageMatrix(endMatrix);
        return true;
    }

    @Override
    public void onClick(View v) {
        if (v.equals(imBack)) {
            AdManager.showTopOn(this, () -> {
                finish();
            });

        } else {
            if (!hasPermission) {
                // 无权限：Toast提示（通过showNoPermission方法实现）
                showNoPermission();
                return;
            }

            // 新增：锁定按钮点击逻辑
            if (v.equals(imLock)) {
                AdManager.showTopOn(this, () -> {
                    isImageLocked = !isImageLocked; // 切换锁定状态
                    imLock.setSelected(isImageLocked); // 更新按钮选中状态（对应selector图标切换）
                    // 可选：添加Toast提示
                    String tip = isImageLocked ? "Image locked" : "Image unlocked";
                    Toast.makeText(this, tip, Toast.LENGTH_SHORT).show();

                });
                return;
            }

            if (v.equals(flashIm)) {
                // 增加camera非空判断，避免崩溃
                if (camera != null) {
                    boolean selected = flashIm.isSelected();
                    flashIm.setSelected(!selected);
                    camera.getCameraControl().enableTorch(!selected);
                } else {
                    // 相机未就绪：Toast提示
                    Toast.makeText(this, "The camera is not ready yet", Toast.LENGTH_SHORT).show();
                }
            } else if (v.equals(imPhoto)) {
                AdManager.showTopOn(this, () -> {
                    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*"); // 限制选择类型为图片
                    intentActivityResultLauncher.launch(intent);
                });
                // 相册按钮：打开相册（限制仅选择图片类型）

            } else if (v.equals(imZoom)) {
                // 缩放按钮：切换选中状态+显示/隐藏SeekBar
                boolean selected = imZoom.isSelected();
                imZoom.setSelected(!selected); // 切换选中状态（自动切换图标）
                if (seekBar.getVisibility() == View.VISIBLE) {
                    seekBar.setVisibility(View.GONE);
                } else {
                    seekBar.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    private void initClick() {
        imBack.setOnClickListener(this);
        flashIm.setOnClickListener(this);
        imPhoto.setOnClickListener(this);
        imZoom.setOnClickListener(this);
        imLock.setOnClickListener(this); // 新增：绑定锁定按钮点击事件

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                float v = (seekBar.getMax() - progress) / 10.0f;
                imageView.setAlpha(v);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
    }

    private void init() {
        cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA;
        permissions = new String[]{Manifest.permission.CAMERA};
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_MEDIA_IMAGES};
        } else {
            permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        }
        if (!checkPermission()) {
            hasPermission = false;
            imageView.setOnTouchListener(null);
            ActivityCompat.requestPermissions(this, permissions, 0);
        } else {
            hasPermission = true;
            imageView.setOnTouchListener(this);
            startCamera();
        }
    }

    private void startCamera() {
        ListenableFuture<ProcessCameraProvider> future = ProcessCameraProvider.getInstance(this);
        future.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = future.get();
                Preview preview = new Preview.Builder().build();
                cameraProvider.unbindAll();
                ImageCapture.Builder builder1 = new ImageCapture.Builder();
                imageCapture = builder1.build();
                camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageCapture);
                range = AppUtils.getRange(camera);
                preview.setSurfaceProvider(previewView.getSurfaceProvider());

                if (curBitmapPath != null) {
                    Bitmap bitmap = AppUtils.loadImageFromAssets(this, curBitmapPath);
                    if (bitmap != null) { // 增加bitmap非空判断
                        imageView.setImageBitmap(bitmap);
                        int width = bitmap.getWidth();
                        int height = bitmap.getHeight();
                        onInitIm(width, height);
                    } else {
                        // 加载位图失败：Toast提示
                        Toast.makeText(this, "Bitmap load failed", Toast.LENGTH_SHORT).show();
                        Log.e("CameraPickerActivity", "Bitmap load failed");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                // 相机初始化失败：Toast提示
                Toast.makeText(this, "Camera initialization unsuccessful", Toast.LENGTH_SHORT).show();
            }
        }, ContextCompat.getMainExecutor(this));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0) {
            if (checkPermission()) {
                hasPermission = true;
                imageView.setOnTouchListener(this);
                startCamera();
            } else {
                hasPermission = false;
                imageView.setOnTouchListener(null);
                // 权限未授予：Toast提示
                Toast.makeText(this, "Camera permission denied", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private boolean checkPermission() {
        boolean result = true;
        for (String per : permissions) {
            if (ActivityCompat.checkSelfPermission(this, per) != PackageManager.PERMISSION_GRANTED) {
                result = false;
                break; // 优化：发现未授权直接返回
            }
        }
        return result;
    }

    private void showNoPermission() {
        // 无权限提示：使用string资源+Toast
        Toast.makeText(this, getString(R.string.permission_fail), Toast.LENGTH_SHORT).show();
    }

    /**
     * 计算Uri对应的文件大小（单位：MB）
     * @param context 上下文
     * @param uri 文件Uri
     * @return 文件大小（MB）
     */
    public static double getUriFileSize(Context context, Uri uri) {
        double fileSize = 0.0;
        ContentResolver contentResolver = context.getContentResolver();
        if ("file".equals(uri.getScheme())) {
            File file = new File(Objects.requireNonNull(uri.getPath()));
            if (file.exists()) {
                fileSize = (double) file.length();
            }
        } else {
            ParcelFileDescriptor pfd = null;
            try {
                pfd = contentResolver.openFileDescriptor(uri, "r");
                if (pfd != null) {
                    fileSize = (double) pfd.getStatSize();
                }
            } catch (Exception e) {
                Log.e("UriUtils", "Error while retrieving file size: " + e.getMessage(), e);
            } finally {
                if (pfd != null) {
                    try {
                        pfd.close();
                    } catch (IOException e) {
                        // ignore
                    }
                }
            }
        }
        return fileSize / 1048576.0; // 转换为MB（1MB = 1024*1024 = 1048576 字节）
    }
}