package com.retrytech.strangerapp.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.session.PlaybackState;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowInsets;
import android.widget.PopupMenu;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.OptIn;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.databinding.DataBindingUtil;
import androidx.media3.common.MediaItem;
import androidx.media3.common.Player;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.ui.PlayerView;

import com.bumptech.glide.Glide;
import com.retrytech.strangerapp.R;
import com.retrytech.strangerapp.databinding.ActivityFakeVideoBinding;
import com.retrytech.strangerapp.databinding.ItemConfirmationPopupBinding;
import com.retrytech.strangerapp.modal.fakeuser.FakeUser;
import com.retrytech.strangerapp.retrofit.Const;
import com.retrytech.strangerapp.utils.SessionManager;

import java.util.Random;

public class FakeVideoActivity extends AppCompatActivity {

    ActivityFakeVideoBinding binding;
    ExoPlayer player;
    private boolean mMuted = false;
    private boolean isFrontCamera = true;
    String videoUrl = "";
    SessionManager sessionManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View decorView = getWindow().getDecorView();
        decorView.setOnApplyWindowInsetsListener((v, insets) -> {
            WindowInsets defaultInsets = v.onApplyWindowInsets(insets);
            return defaultInsets.replaceSystemWindowInsets(
                    defaultInsets.getSystemWindowInsetLeft(),
                    0,
                    defaultInsets.getSystemWindowInsetRight(),
                    defaultInsets.getSystemWindowInsetBottom());
        });
        ViewCompat.requestApplyInsets(decorView);
        getWindow().setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));

        binding = DataBindingUtil.setContentView(this, R.layout.activity_fake_video);
        sessionManager = new SessionManager(this);
        FakeUser fakeUser = sessionManager.getFakeUser();
        if (fakeUser != null && !fakeUser.getData().isEmpty()) {
            int random = new Random().nextInt((fakeUser.getData().size()));
            videoUrl = Const.ITEM_URL + fakeUser.getData().get(random).getVideo();
            binding.tvUserName.setText(fakeUser.getData().get(random).getFullname());
            binding.tvUserLocation.setText(fakeUser.getData().get(random).getLocation());
            Glide.with(this).load(Const.ITEM_URL + fakeUser.getData().get(random).getImage()).circleCrop().into(binding.imgUser);

            fakeUser.getData().remove(random);
            sessionManager.saveFakeUsers(fakeUser);
        }
        setVideo();

    }

    @OptIn(markerClass = UnstableApi.class)
    private void setVideo() {
        player = new ExoPlayer.Builder(this).build();
        binding.playerview.setPlayer(player);
        binding.playerview.setShowBuffering(PlayerView.SHOW_BUFFERING_WHEN_PLAYING);
        Uri uri = Uri.parse(videoUrl);
        player.setMediaItem(new MediaItem.Builder().setUri(uri).build());
        player.setPlayWhenReady(true);
        player.prepare();
        player.addListener(new Player.Listener() {
            @Override
            public void onPlaybackStateChanged(int playbackState) {
                Player.Listener.super.onPlaybackStateChanged(playbackState);
                if (playbackState == Player.STATE_ENDED){
                    getOnBackPressedDispatcher().onBackPressed();
                }

            }
        });
        initCamera();
        binding.ivMenu.setOnClickListener(view -> {
            PopupMenu popupMenu = new PopupMenu(this, view);
            popupMenu.inflate(R.menu.call_menu);
            popupMenu.setOnMenuItemClickListener(item -> {
                if (item.getItemId() == R.id.menu_report) {
                    startActivity(new Intent(FakeVideoActivity.this, ReportActivity.class));
                    onBackPressed();
                } else if (item.getItemId() == R.id.menu_block) {
                    Dialog dialog = new Dialog(this);
                    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    View view1 = LayoutInflater.from(this).inflate(R.layout.item_confirmation_popup, null, false);
                    ItemConfirmationPopupBinding confirmationPopupBinding = DataBindingUtil.bind(view1);

                    if (confirmationPopupBinding != null) {
                        confirmationPopupBinding.tvMessage.setText(getResources().getString(R.string.block_acc_message));

                        confirmationPopupBinding.btnYes.setOnClickListener(v -> {
                            dialog.dismiss();
                            Toast.makeText(this, R.string.user_blocked_successfully, Toast.LENGTH_SHORT).show();
                            onBackPressed();
                        });
                        confirmationPopupBinding.btnCancel.setOnClickListener(v -> dialog.dismiss());
                        dialog.setContentView(confirmationPopupBinding.getRoot());
                        dialog.setCancelable(false);
                        dialog.show();
                    }
                }
                return true;
            });
            popupMenu.show();
        });
    }

    private void initCamera() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
                    1);
        } else {
            binding.surfaceCamera.bindToLifecycle(this);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        initCamera();
    }

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

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        player.release();
    }

    public void onLocalAudioMuteClicked(View view) {
        Log.d("TAG", "onLocalAudioMuteClicked: " + view);

        mMuted = !mMuted;
        int res = mMuted ? R.drawable.btn_mute : R.drawable.btn_unmute;
        binding.btnMute.setImageResource(res);
    }

    @Override
    protected void onPause() {
        super.onPause();
        player.setVolume(0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        player.setVolume(1);
    }

    public void onSwitchCameraClicked(View view) {
        isFrontCamera = !isFrontCamera;
        binding.surfaceCamera.toggleCamera();
    }

    public void onCallClicked(View view) {
        onBackPressed();
    }
}