package com.draw.painting.canvas.presentation;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
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 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.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.draw.painting.canvas.ad.AdsInsUtil;
import com.draw.painting.canvas.ad.LoadListener;
import com.draw.painting.canvas.ad.ShowListener;
import com.google.common.util.concurrent.ListenableFuture;
import com.draw.painting.canvas.CanvasApp;
import com.draw.painting.canvas.R;
import com.draw.painting.canvas.core.SystemHelper;
import com.tradplus.ads.base.bean.TPAdInfo;

import org.jetbrains.annotations.NotNull;

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

public class ARCameraActivity 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 TextView tvOpacityValue;

    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, imBack, opacityIm;
    private View imZoom, imPhoto, btnFlashContainer;
    private View opacityContainer;
    private Runnable hidePercentageRunnable;

    private String curBitmapPath;
    private boolean hasPermission = false;
    private ActivityResultLauncher<PickVisualMediaRequest> pickImageLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // 启用 EdgeToEdge 全屏显示
        SystemHelper.enableEdgeToEdge(this);
        
        // 设置状态栏图标为浅色（白色），因为相机预览背景可能较深
        SystemHelper.setSystemBarsLight(this, false, true);
        
        // 确保窗口背景透明
        SystemHelper.setTransparentWindowBackground(this);
        
        setContentView(R.layout.activity_ar_camera);

        AdsInsUtil.INSTANCE.showAd(this, AdsInsUtil.Placement.TOP_ON_AD_THREE, new ShowListener() {
            @Override
            public void onAdShown(@org.jetbrains.annotations.Nullable TPAdInfo ad) {
                loadAd();
            }

            @Override
            public void onAdClosed() {
                loadAd();
            }
        });
        
        previewView = findViewById(R.id.preview);
        imageView = findViewById(R.id.image);
        imBack = findViewById(R.id.back);
        
        // 相机界面全屏沉浸式设置：让预览延伸到状态栏，返回按钮添加顶部margin
        View rootView = findViewById(android.R.id.content);
        SystemHelper.setupCameraFullScreen(rootView, imBack, 8);

        seekBar = findViewById(R.id.seekbar);
        tvOpacityValue = findViewById(R.id.tv_opacity_value);
        opacityContainer = findViewById(R.id.opacity_container);
        
        // 新布局：按钮容器
        imZoom = findViewById(R.id.im_zoom);
        imPhoto = findViewById(R.id.im_photo);
        btnFlashContainer = findViewById(R.id.btn_flash_container);
        flashIm = findViewById(R.id.im_flash);
        opacityIm = findViewById(R.id.im_opacity);

        curBitmapPath = getIntent().getStringExtra(CanvasApp.Key_Camera);
        String customImageUri = getIntent().getStringExtra("custom_image_uri");

        pickImageLauncher = registerForActivityResult(
                new ActivityResultContracts.PickVisualMedia(), result -> {
                    if(result==null){
                        Toast.makeText(this,getString(R.string.permission_fail),Toast.LENGTH_SHORT).show();
                        Log.d("-------------------tt","-------imageUri-111-null");
                        return;
                    }
                    double uriFileSize = getUriFileSize(ARCameraActivity.this,result);
                    if (uriFileSize >=4){
                        Toast.makeText(this,getString(R.string.file_fail),Toast.LENGTH_SHORT).show();

                        Log.d("-------------tt","-------imageUri---222-uriFileSize="+uriFileSize);
                        return;
                    }
                    Log.d("-------------tt","-------imageUri---333-uriFileSize="+uriFileSize);
                    imageView.setImageURI(result);
        });

        init();
        initClick();
        
        // 如果从主界面传递了自定义图片URI，直接加载
        if (customImageUri != null) {
            Uri uri = Uri.parse(customImageUri);
            double uriFileSize = getUriFileSize(ARCameraActivity.this, uri);
            if (uriFileSize < 4) {
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                    imageView.setImageBitmap(bitmap);
                    int width = bitmap.getWidth();
                    int height = bitmap.getHeight();
                    onInitIm(width, height);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(this, getString(R.string.permission_fail), Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, getString(R.string.file_fail), Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void onInitIm(float imW, float imH) {
        Point screen = SystemHelper.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) {
        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 = SystemHelper.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 = SystemHelper.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)) {
            finish();
        } else {
            if (!hasPermission && !v.equals(imZoom)) {
                showNoPermission();
                return;
            }
            if (v.equals(btnFlashContainer)) {
                if (camera == null) {
                    return;
                }
                boolean selected = flashIm.isSelected();
                flashIm.setSelected(!selected);
                camera.getCameraControl().enableTorch(!selected);
            } else if (v.equals(imPhoto)) {
                pickImageLauncher.launch(
                        new PickVisualMediaRequest.Builder()
                                .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                                .build()
                );
            } else if (v.equals(imZoom)) {
                // 切换透明度控制面板显示/隐藏
                toggleOpacityPanel();
            }
        }
    }

    private void initClick() {
        imBack.setOnClickListener(this);
        btnFlashContainer.setOnClickListener(this);
        imPhoto.setOnClickListener(this);
        imZoom.setOnClickListener(this);
        
        // 设置透明度图标初始状态为未选中
        opacityIm.setSelected(false);
        
        // 点击相机预览区域（空白区域）收起透明度面板
        previewView.setOnClickListener(v -> {
            if (opacityContainer.getVisibility() == View.VISIBLE) {
                hideOpacityPanel();
            }
        });
        
        // 初始化隐藏百分比的延迟任务
        hidePercentageRunnable = () -> {
            tvOpacityValue.animate()
                .alpha(0f)
                .setDuration(200)
                .start();
        };
        
        // 百分比初始为透明（隐藏）
        tvOpacityValue.setAlpha(0f);
        tvOpacityValue.setText("100%");
        
        // SeekBar 监听器：调节透明度并显示百分比
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // 计算透明度（0-10 映射到 0.0-1.0）
                float alpha = progress / 10.0f;
                imageView.setAlpha(alpha);
                
                // 更新百分比显示
                int percentage = (int) (alpha * 100);
                tvOpacityValue.setText(percentage + "%");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 开始拖动时显示百分比
                tvOpacityValue.clearAnimation();
                tvOpacityValue.animate()
                    .alpha(1f)
                    .setDuration(150)
                    .start();
                
                // 取消之前的隐藏任务
                tvOpacityValue.removeCallbacks(hidePercentageRunnable);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 停止拖动后延迟 1 秒隐藏百分比
                tvOpacityValue.postDelayed(hidePercentageRunnable, 1000);
            }
        });
    }
    
    /**
     * 切换透明度面板显示/隐藏（带动画）
     */
    private void toggleOpacityPanel() {
        if (opacityContainer.getVisibility() == View.VISIBLE) {
            hideOpacityPanel();
        } else {
            showOpacityPanel();
        }
    }
    
    /**
     * 显示透明度面板（从底部滑入）
     */
    private void showOpacityPanel() {
        opacityContainer.setVisibility(View.VISIBLE);
        opacityContainer.setTranslationY(opacityContainer.getHeight());
        opacityContainer.animate()
            .translationY(0)
            .setDuration(250)
            .start();
        opacityIm.setSelected(true);
    }
    
    /**
     * 隐藏透明度面板（滑出到底部）
     */
    private void hideOpacityPanel() {
        opacityContainer.animate()
            .translationY(opacityContainer.getHeight())
            .setDuration(200)
            .withEndAction(() -> {
                opacityContainer.setVisibility(View.GONE);
                opacityContainer.setTranslationY(0);
            })
            .start();
        opacityIm.setSelected(false);
        
        // 隐藏面板时也隐藏百分比
        tvOpacityValue.removeCallbacks(hidePercentageRunnable);
        tvOpacityValue.animate()
            .alpha(0f)
            .setDuration(150)
            .start();
    }

    private void init() {
        cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA;
        permissions = new String[]{android.Manifest.permission.CAMERA};
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions = new String[]{android.Manifest.permission.CAMERA};
        } else {
            permissions = new String[]{android.Manifest.permission.CAMERA};
        }
        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 = SystemHelper.getRange(camera);
                preview.setSurfaceProvider(previewView.getSurfaceProvider());

                if (curBitmapPath != null) {
                    Bitmap bitmap = SystemHelper.loadImageFromAssets(this, curBitmapPath);
                    imageView.setImageBitmap(bitmap);
                    int width = bitmap.getWidth();
                    int height = bitmap.getHeight();
                    onInitIm(width, height);


                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }, 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);
            }

        }
    }


    private boolean checkPermission() {
        boolean result = true;
        for (String per : permissions) {
            if (ActivityCompat.checkSelfPermission(this, per) != PackageManager.PERMISSION_GRANTED) {
                result = false;
            }
        }
        return result;

    }

    private void showNoPermission() {
        Toast.makeText(this, getString(R.string.permission_fail), Toast.LENGTH_SHORT).show();
    }

    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;
    }


    private void loadAd(){
        AdsInsUtil.INSTANCE.loadAd(this, AdsInsUtil.Placement.TOP_ON_AD_THREE, new LoadListener() {
            @Override
            public void loadFailed(@NotNull String error) {

            }
        });
    }
}

