package com.ar.ardrawingboard.ui.activity;

import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
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.ImageCaptureException;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.core.content.ContextCompat;

import com.ar.ardrawingboard.R;
import com.ar.ardrawingboard.databinding.ActivityBoardBinding;
import com.ar.ardrawingboard.topon.AdManager;
import com.ar.ardrawingboard.topon.onActionListener;
import com.ar.ardrawingboard.util.CommonUtils;
import com.ar.ardrawingboard.util.ImageUtils;
import com.ar.ardrawingboard.util.PermissionUtils;
import com.ar.ardrawingboard.util.TouchUtils;
import com.google.common.util.concurrent.ListenableFuture;

public class BoardActivity extends AppCompatActivity {
    private ActivityBoardBinding uiBinding;
    private ImageView displayImageView;
    private Bitmap loadedBitmap;
    private Camera activeCamera;
    private ImageCapture photoCapture;
    private boolean flashEnabled = false;
    private boolean mirrorEnabled = false;

    private static final int CAMERA_PERMISSION_CODE = 100;
    private static final int STORAGE_PERMISSION_CODE = 101;

    private final ActivityResultLauncher<Intent> imagePickerLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                    Uri imageUri = result.getData().getData();
                    if (imageUri != null) {
                        displayImageView.setImageURI(imageUri);
                    }
                }
            });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initializeUi();
        configureImageView();
        setupEventHandlers();
        handleIntentImage();
        initializeCameraIfPermitted();
    }

    private void initializeUi() {
        uiBinding = ActivityBoardBinding.inflate(getLayoutInflater());
        setContentView(uiBinding.getRoot());
        displayImageView = uiBinding.imageFull;

        AdManager.loadAllAd();
        AdManager.showTopOn(this, new onActionListener() {
            @Override
            public void onAction() {

            }
        });
    }

    private void configureImageView() {
        displayImageView.setOnTouchListener((view, event) -> TouchUtils.handleTouchEvent((ImageView) view, event));
    }

    private void setupEventHandlers() {
        uiBinding.seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                displayImageView.setAlpha((100 - progress) / 100f);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

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

        uiBinding.importImage.setOnClickListener(v -> {
            AdManager.showTopOn(this, new onActionListener() {
                @Override
                public void onAction() {
                    launchImagePicker();
                }
            });
        });
        uiBinding.light.setOnClickListener(v -> switchFlash());
        uiBinding.back.setOnClickListener(v -> {
            AdManager.showTopOn(this, new onActionListener() {
                @Override
                public void onAction() {
                    finish();
                }
            });
        });
        uiBinding.reversal.setOnClickListener(v -> applyMirrorEffect());
        uiBinding.play.setOnClickListener(v -> {
            AdManager.showTopOn(this, new onActionListener() {
                @Override
                public void onAction() {
                    capturePhoto();
                }
            });
        });
    }

    private void handleIntentImage() {
        String imagePath = getIntent().getStringExtra("imagePath");
        if (imagePath != null) {
            loadAndDisplayImage(imagePath);
        }
    }

    private void initializeCameraIfPermitted() {
        String[] requiredPermissions = PermissionUtils.getCameraAndStoragePermissions();
        if (PermissionUtils.hasPermissions(this, requiredPermissions)) {
            launchCamera();
        } else {
            PermissionUtils.requestPermissions(this, requiredPermissions, CAMERA_PERMISSION_CODE);
        }
    }

    private void launchCamera() {
        ListenableFuture<ProcessCameraProvider> providerFuture = ProcessCameraProvider.getInstance(this);
        providerFuture.addListener(() -> {
            try {
                ProcessCameraProvider provider = providerFuture.get();
                setupCameraUseCases(provider);
            } catch (Exception e) {
                Toast.makeText(this, "Camera initialization failed", Toast.LENGTH_SHORT).show();
            }
        }, ContextCompat.getMainExecutor(this));
    }

    private void setupCameraUseCases(ProcessCameraProvider provider) {
        Preview preview = new Preview.Builder().build();
        CameraSelector cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA;
        photoCapture = new ImageCapture.Builder().build();

        preview.setSurfaceProvider(uiBinding.preview.getSurfaceProvider());
        provider.unbindAll();
        activeCamera = provider.bindToLifecycle(this, cameraSelector, preview, photoCapture);

        if (loadedBitmap != null) {
            TouchUtils.initPosition(displayImageView, loadedBitmap, CommonUtils.getScreenSize(this));
        }
    }

    private void capturePhoto() {
        if (photoCapture == null) {
            Toast.makeText(this, "Camera not ready", Toast.LENGTH_SHORT).show();
            return;
        }

        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, "photo_" + System.currentTimeMillis() + ".jpg");
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
        contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);

        ImageCapture.OutputFileOptions options = new ImageCapture.OutputFileOptions.Builder(
                getContentResolver(), MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues).build();

        photoCapture.takePicture(options, ContextCompat.getMainExecutor(this), new ImageCapture.OnImageSavedCallback() {
            @Override
            public void onImageSaved(@NonNull ImageCapture.OutputFileResults results) {
                Toast.makeText(BoardActivity.this, "Photo captured successfully", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(@NonNull ImageCaptureException error) {
                Toast.makeText(BoardActivity.this, "Capture failed: " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void switchFlash() {
        if (activeCamera != null) {
            flashEnabled = !flashEnabled;
            activeCamera.getCameraControl().enableTorch(flashEnabled);
            uiBinding.light.setImageResource(flashEnabled ? R.drawable.flash : R.drawable.un_flash);
        }
    }

    private void applyMirrorEffect() {
        mirrorEnabled = !mirrorEnabled;
        displayImageView.setScaleX(mirrorEnabled ? -1f : 1f);
        uiBinding.reversal.setImageResource(mirrorEnabled ? R.drawable.reversal : R.drawable.un_reversal);
    }

    private void launchImagePicker() {
        String[] permissions = PermissionUtils.getCameraAndStoragePermissions();
        if (PermissionUtils.hasPermissions(this, permissions)) {
            Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            imagePickerLauncher.launch(pickIntent);
        } else {
            PermissionUtils.requestPermissions(this, permissions, STORAGE_PERMISSION_CODE);
        }
    }

    private void loadAndDisplayImage(String path) {
        if (path.startsWith("/data/user/")) {
            loadedBitmap = ImageUtils.loadBitmapFromStorage(path);
        } else {
            loadedBitmap = ImageUtils.loadBitmapFromAssets(this, path);
        }

        if (loadedBitmap != null) {
            ImageUtils.displayImageToImageView(displayImageView, loadedBitmap);
        } else {
            Toast.makeText(this, "Image loading failed", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (PermissionUtils.handlePermissionsResult(grantResults)) {
            if (requestCode == CAMERA_PERMISSION_CODE) {
                launchCamera();
            } else if (requestCode == STORAGE_PERMISSION_CODE) {
                launchImagePicker();
            }
        } else {
            Toast.makeText(this, "Permissions not granted", Toast.LENGTH_SHORT).show();
        }
    }
}