package com.example.status_saver;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

import com.bumptech.glide.Glide;
import com.cv.status.R;
import com.example.status_saver.adapters.BottomSheetAdapter;
import com.example.status_saver.adapters.SaveBottomAdapter;
import com.example.status_saver.intefaces.OnSaveItemClickListeners;
import com.example.status_saver.utils.Constant;
import com.example.status_saver.utils.FirebaseAnalytic;
import com.example.status_saver.utils.PathListSingelton;
import com.example.status_saver.utils.SingleMediaScanner;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.firebase.analytics.FirebaseAnalytics;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

public class PreViewActivity extends AppCompatActivity implements OnSaveItemClickListeners {
    ImageView imagePreview;
    CardView imagecard;
    VideoView videoPreview;
    String video_path;
    String location;
    Intent intent;
    private BottomSheetBehavior<View> bottomSheetBehavior;
    private SaveBottomAdapter saveBottomAdapter;

    Button save, share, repost, delete;
    Toolbar toolbar;

    private void init() {
        toolbar = findViewById(R.id.toolbar_preview);
        save = findViewById(R.id.save);
        share = findViewById(R.id.share);
        repost = findViewById(R.id.repost);
        delete = findViewById(R.id.delete);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pre_view);

        init();
        View bottomSheet = findViewById(R.id.persistent_bottom_sheet);
        bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        bottomSheetBehavior.setHideable(false);
        bottomSheetBehavior.setSkipCollapsed(true);
        bottomSheetBehavior.setPeekHeight(500, true);
        bottomSheetBehavior.setMaxHeight(1550);

        RecyclerView image_recycle = findViewById(R.id.image_bottom);
        image_recycle.setLayoutManager(new GridLayoutManager(this, 3));
        bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {

            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {

            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                bottomSheetBehavior.setMaxHeight(1550);

            }

        });

        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("Image");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        if (toolbar != null) {
        }
        share.setVisibility(View.GONE);
        repost.setVisibility(View.GONE);
        delete.setVisibility(View.GONE);
        imagePreview = findViewById(R.id.image_preview);
        imagecard = findViewById(R.id.imagecard);
        videoPreview = findViewById(R.id.video_preview);
        intent = getIntent();
        video_path = intent.getStringExtra("video_path");
        location = intent.getStringExtra("location");
        if (location.equals("Save")) {
            saveBottomAdapter = new SaveBottomAdapter(this, PathListSingelton.INSTANCE.getsaveAll(), this);
            image_recycle.setAdapter(saveBottomAdapter);
            save.setVisibility(View.GONE);
            share.setVisibility(View.VISIBLE);
            repost.setVisibility(View.VISIBLE);
            delete.setVisibility(View.VISIBLE);
        } else if (location.equals("Recent")) {
            if (video_path.endsWith(".jpg") || video_path.endsWith(".png")) {
                Glide.with(this).load(video_path).into(imagePreview);
            }


        } else if (location.equals("MyStatus")) {
            if (video_path.endsWith(".jpg") || video_path.endsWith(".png")) {
                image_recycle.setAdapter(new BottomSheetAdapter(this, PathListSingelton.INSTANCE.getStatusImageList()));
            } else if (video_path.endsWith(".mp4")) {
                image_recycle.setAdapter(new BottomSheetAdapter(this, PathListSingelton.INSTANCE.getStatusVideoList()));
            }
            save.setVisibility(View.VISIBLE);
            share.setVisibility(View.GONE);
            repost.setVisibility(View.GONE);
        } else if (location.equals("recover")) {
            if (video_path.endsWith(".png") || video_path.endsWith(".jpg")) {
                saveBottomAdapter = new SaveBottomAdapter(this, PathListSingelton.INSTANCE.getRecoverImages(), this);
            } else if (video_path.endsWith(".mp4")) {
                saveBottomAdapter = new SaveBottomAdapter(this, PathListSingelton.INSTANCE.getRecoverVideos(), this);

            }
            image_recycle.setAdapter(saveBottomAdapter);
            save.setVisibility(View.GONE);
            share.setVisibility(View.VISIBLE);
            repost.setVisibility(View.VISIBLE);
            delete.setVisibility(View.GONE);
        }

        changeImageWithPAth(video_path);
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (saveBottomAdapter.shareSelectionList().size() > 0) {
                    for (String filePath : saveBottomAdapter.shareSelectionList()) {
                        File file = new File(filePath);
                        if (file.delete()) {
                            if (video_path.contains(".jpg") || video_path.contains(".png")) {
                                PathListSingelton.INSTANCE.getsaveAll().remove(video_path);
                                PathListSingelton.INSTANCE.getsaveImages().remove(video_path);
                            } else if (video_path.contains(".mp4")) {
                                PathListSingelton.INSTANCE.getsaveAll().remove(video_path);
                                PathListSingelton.INSTANCE.getsaveVideos().remove(video_path);
                            }
                            getSaveItem();
                            Toast.makeText(PreViewActivity.this, "Deleted Successfully ", Toast.LENGTH_SHORT).show();
                            finish();
                        } else
                            Toast.makeText(PreViewActivity.this, "Not Deleted ", Toast.LENGTH_SHORT).show();

                    }
                } else {

                    File file = new File(video_path);
                    System.out.println("PreViewActivity.onClick file   " + file);
                    if (file.delete()) {
                        if (video_path.contains(".jpg") || video_path.contains(".png")) {
                            PathListSingelton.INSTANCE.getsaveAll().remove(video_path);
                            PathListSingelton.INSTANCE.getsaveImages().remove(video_path);
                        } else if (video_path.contains(".mp4")) {
                            getSaveItem();
                            PathListSingelton.INSTANCE.getsaveAll().remove(video_path);
                            PathListSingelton.INSTANCE.getsaveVideos().remove(video_path);
                        }
                        getSaveItem();

//                     Constant.INSTANCE.getSaveData(PreViewActivity.this);
                        System.out.println("PreViewActivity.onClick  after remove item List size");
                        System.out.println("PreViewActivity.onClick....save all 2222....." + PathListSingelton.INSTANCE.getsaveAll().size());
                        System.out.println("PreViewActivity.onClick....save image 2222....." + PathListSingelton.INSTANCE.getsaveImages().size());
                        Toast.makeText(PreViewActivity.this, "Deleted Successfully ", Toast.LENGTH_SHORT).show();
                        finish();
                    } else
                        Toast.makeText(PreViewActivity.this, "Not Deleted ", Toast.LENGTH_SHORT).show();

                }
                FirebaseAnalytics.getInstance(PreViewActivity.this).logEvent(FirebaseAnalytic.INSTANCE.getDELETE(), null);

            }
        });
        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (saveBottomAdapter.shareSelectionList().size() > 0) {
                    System.out.println("PreViewActivity.onClick file share " + saveBottomAdapter.shareSelectionList().size());
                    ArrayList<Uri> uris = new ArrayList<>();
                    for (String filePath : saveBottomAdapter.shareSelectionList()) {
                        File file = new File(filePath);
                        // Make sure the file exists and is readable
                        if (file.exists() && file.canRead()) {
                            Uri contentUri = FileProvider.getUriForFile(PreViewActivity.this, getPackageName() + ".provider", file);
                            uris.add(contentUri);
                        }
                    }
                    if (!uris.isEmpty()) {
                        Intent shareIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
                        shareIntent.setType("*/*"); // Set the MIME type as needed
                        shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
                        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        someActivityResultLauncher.launch(shareIntent);
                    }


                } else {
                    Intent shareIntent = new Intent(Intent.ACTION_SEND);
                    shareIntent.setType("image/jpeg");
                    shareIntent.setType("video/mp4");
                    File file = new File(video_path);
                    System.out.println("PreViewActivity.onClick " + getPackageName());
                    Uri contentUri = FileProvider.getUriForFile(PreViewActivity.this, getPackageName() + ".provider", file);
                    shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
                    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    someActivityResultLauncher.launch(shareIntent);
                }

                FirebaseAnalytics.getInstance(PreViewActivity.this).logEvent(FirebaseAnalytic.INSTANCE.getSHARE(), null);
            }

        });

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        copyFile(Uri.parse(video_path), PreViewActivity.this);
                        save.setVisibility(View.GONE);
                    } else {
                        copyFileBelow10(Uri.parse(video_path), PreViewActivity.this);
                        save.setVisibility(View.GONE);
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                FirebaseAnalytics.getInstance(PreViewActivity.this).logEvent(FirebaseAnalytic.INSTANCE.getSAVE(), null);
            }
        });
        repost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (saveBottomAdapter.shareSelectionList().size() > 0) {
                    System.out.println("PreViewActivity.onClick file share " + saveBottomAdapter.shareSelectionList().size());
                    ArrayList<Uri> uris = new ArrayList<>();
                    for (String filePath : saveBottomAdapter.shareSelectionList()) {
                        File file = new File(filePath);
                        // Make sure the file exists and is readable
                        if (file.exists() && file.canRead()) {
                            Uri contentUri = FileProvider.getUriForFile(PreViewActivity.this, getPackageName() + ".provider", file);
                            uris.add(contentUri);
                        }
                    }
                    if (!uris.isEmpty()) {
                        Intent shareIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
                        shareIntent.setType("*/*"); // Set the MIME type as needed
                        shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
                        shareIntent.setPackage("com.whatsapp");
                        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        someActivityResultLauncher.launch(shareIntent);
                    }
                } else {
                    Intent sharewa = new Intent(Intent.ACTION_SEND);
                    sharewa.setType("image/jpeg");
                    sharewa.setType("video/mp4");
                    File file = new File(video_path);
                    sharewa.setPackage("com.whatsapp");
                    Uri imageUri = FileProvider.getUriForFile(PreViewActivity.this, getPackageName() + ".provider", file);
                    sharewa.putExtra(Intent.EXTRA_STREAM, imageUri);
                    sharewa.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    someActivityResultLauncher.launch(sharewa);
                }

                FirebaseAnalytics.getInstance(PreViewActivity.this).logEvent(FirebaseAnalytic.INSTANCE.getREPOST(), null);
            }
        });
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    public void copyFile(Uri uri, Context context) throws IOException {
        File file = new File(context.getExternalFilesDir("StatusDownloader").getPath());
        if (!file.exists()) {
            if (!file.mkdirs()) {

            }
        }
        String fileName;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
        String currentDateTime = sdf.format(new Date());
        if (uri.getPath().endsWith(".mp4")) {
            fileName = "VID_" + currentDateTime + ".mp4";
        } else {
            fileName = "IMG_" + currentDateTime + ".jpg";
        }
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                ContentValues values = new ContentValues();
                Uri destinationUri;
                values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
                values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/CVI_saver");
                Uri collectionUri;
                if (uri.getPath().endsWith(".mp4")) {
                    values.put(MediaStore.MediaColumns.MIME_TYPE, "video/*");
                    collectionUri = MediaStore.Video.Media.getContentUri(
                            MediaStore.VOLUME_EXTERNAL_PRIMARY);
                } else {
                    values.put(MediaStore.MediaColumns.MIME_TYPE, "image/*");
                    collectionUri = MediaStore.Images.Media.getContentUri(
                            MediaStore.VOLUME_EXTERNAL_PRIMARY);
                }

                destinationUri = context.getContentResolver().insert(collectionUri, values);

                InputStream inputStream = context.getContentResolver().openInputStream(uri);
                OutputStream outputStream = context.getContentResolver().openOutputStream(destinationUri);
                IOUtils.copy(inputStream, outputStream);
                Toast.makeText(context, "Downloaded", Toast.LENGTH_SHORT).show();
                LottieDialog lottieDialog = new LottieDialog(PreViewActivity.this, "Downloaded");
                lottieDialog.show();

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void copyFileBelow10(Uri uri, Context context) {

        File file = new File(context.getExternalFilesDir("StatusDownloader").getPath());
        if (!file.exists()) {
            if (!file.mkdirs()) {

            }
        }

        String fileName;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
        String currentDateTime = sdf.format(new Date());

        if (uri.getPath().contains(".mp4")) {
            fileName = "VID_" + currentDateTime + ".mp4";
        } else {
            fileName = "IMG_" + currentDateTime + ".jpg";
        }

        File destFile = new File(file + File.separator + fileName);

        try {

            org.apache.commons.io.FileUtils.copyFile(new File(video_path), destFile);
            //noinspection ResultOfMethodCallIgnored
            destFile.setLastModified(System.currentTimeMillis());
            new SingleMediaScanner(context, file);
//            Toast.makeText(context, "Downloaded SuccessFull", Toast.LENGTH_SHORT).show();
            LottieDialog lottieDialog = new LottieDialog(PreViewActivity.this, "Downloaded");
            lottieDialog.show();

//        Uri data = FileProvider.getUriForFile(context, context.getPackageName(),
//                new File(destFile.getAbsolutePath()));


        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    System.out.println("PreViewActivity.onActivityResult " + result.getResultCode());
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        // Here, no request code
                        // Toast.makeText(PreViewActivity.this, "Success fully post ", Toast.LENGTH_SHORT).show();
                        LottieDialog lottieDialog = new LottieDialog(PreViewActivity.this, "Shared Successfully");
                        lottieDialog.show();
                    }
                }
            });


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == android.R.id.home) {
            // Handle the click event here
            onBackPressed(); // Example: Call onBackPressed() to navigate back
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Override
    public void onItemClick(String path) {
        System.out.println("PreViewActivity.onItemClick " + path);
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        changeImageWithPAth(path);
    }

    private void changeImageWithPAth(String path) {
        if (path.contains(".jpg") || path.contains(".png")) {
            imagePreview.setVisibility(View.VISIBLE);
            imagecard.setVisibility(View.VISIBLE);
            videoPreview.setVisibility(View.INVISIBLE);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            getSupportActionBar().setTitle("Image");
            Glide.with(this).load(path).into(imagePreview);
        } else if (path.contains(".mp4")) {
            imagePreview.setVisibility(View.INVISIBLE);
            imagecard.setVisibility(View.INVISIBLE);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            videoPreview.setVisibility(View.VISIBLE);
            Uri video_uri = Uri.parse(path);
            getSupportActionBar().setTitle("Video");
            videoPreview.setVideoURI(video_uri);
            MediaController mediaController = new MediaController(this);
            mediaController.setAnchorView(videoPreview);
            mediaController.setMediaPlayer(videoPreview);
            // videoPreview.setMediaController(mediaController);
            videoPreview.start();
        }
        videoPreview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
//                 videoPreview.setMediaController(mediaController);

            }
        });
    }

    private void getSaveItem() {
        PathListSingelton.INSTANCE.getsaveImages().clear();
        PathListSingelton.INSTANCE.getsaveVideos().clear();
        PathListSingelton.INSTANCE.getsaveAll().clear();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Constant.INSTANCE.getSaveData(PreViewActivity.this);
            }
        }).start();

    }

    @Override
    protected void onResume() {
        super.onResume();

    }
}