package llc.arma.ble.app.ui

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.Intent
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.os.Build
import android.os.Bundle
import android.view.SurfaceView
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.core.view.WindowCompat
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.rememberMultiplePermissionsState
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import llc.arma.ble.app.ui.common.BottomState
import llc.arma.ble.app.ui.common.LocalBottomDialogState
import llc.arma.ble.app.ui.screen.main.MainScreen
import llc.arma.ble.app.ui.theme.BleTheme


@AndroidEntryPoint
class MainActivity : ComponentActivity() {

    @SuppressLint("MissingPermission")
    @OptIn(ExperimentalPermissionsApi::class, ExperimentalMaterialApi::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val mBluetoothAdapter = (getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter

        WindowCompat.setDecorFitsSystemWindows(window, false)

        installSplashScreen()

        setContent {

            BleTheme {

                val modalState =
                    rememberModalBottomSheetState(
                        skipHalfExpanded = true,
                        initialValue = ModalBottomSheetValue.Hidden
                    )

                var sheetContent by remember() {
                    mutableStateOf<@Composable () -> Unit>({})
                }

                if(modalState.currentValue == ModalBottomSheetValue.Hidden){
                    sheetContent = {}
                }

                CompositionLocalProvider(
                    LocalBottomDialogState provides BottomState(
                        sheetState = modalState,
                        setContent = {
                            sheetContent = it
                        }
                    )
                ) {

                    ModalBottomSheetLayout(
                        sheetShape = RoundedCornerShape(
                            topStart = 25.dp,
                            topEnd = 25.dp
                        ),
                        sheetElevation = 0.dp,
                        sheetState = modalState,
                        sheetContent = {

                            val scope = rememberCoroutineScope()

                            Column(
                                horizontalAlignment = Alignment.CenterHorizontally
                            ) {

                                Surface(
                                    modifier = Modifier.fillMaxWidth()
                                ) {

                                    Column(
                                        modifier = Modifier.statusBarsPadding().navigationBarsPadding()
                                    ) {

                                        Spacer(modifier = Modifier.height(14.dp))

                                        Surface(
                                            shape = CircleShape,
                                            color = MaterialTheme.colorScheme.primary.copy(alpha = 0.7f),
                                            modifier = Modifier
                                                .align(Alignment.CenterHorizontally)
                                                .size(
                                                    width = 54.dp,
                                                    height = 5.dp
                                                )

                                        ) {}

                                        Spacer(modifier = Modifier.height(12.dp))

                                        sheetContent()

                                    }

                                }
                            }

                            BackHandler(modalState.isVisible) {
                                scope.launch { modalState.hide() }
                            }

                        },
                        content = {

                            Surface(
                                modifier = Modifier
                                    .fillMaxSize()
                                    .navigationBarsPadding(),
                                color = MaterialTheme.colorScheme.background
                            ) {

                                val multiplePermissionsState =

                                    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {

                                        rememberMultiplePermissionsState(
                                            listOf(
                                                Manifest.permission.READ_MEDIA_VIDEO,
                                                Manifest.permission.READ_MEDIA_IMAGES,
                                                Manifest.permission.BLUETOOTH_SCAN,
                                                Manifest.permission.BLUETOOTH_CONNECT
                                            )
                                        )

                                    }else{
                                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                                            rememberMultiplePermissionsState(
                                                listOf(
                                                    Manifest.permission.READ_EXTERNAL_STORAGE,
                                                    Manifest.permission.BLUETOOTH_SCAN,
                                                    Manifest.permission.BLUETOOTH_CONNECT
                                                )
                                            )
                                        } else {
                                            rememberMultiplePermissionsState(
                                                listOf(
                                                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                                    Manifest.permission.READ_EXTERNAL_STORAGE,
                                                    Manifest.permission.ACCESS_FINE_LOCATION,
                                                    Manifest.permission.ACCESS_COARSE_LOCATION
                                                )
                                            )
                                        }
                                    }

                                var bleEnabled by remember {
                                    mutableStateOf(mBluetoothAdapter.isEnabled)
                                }

                                val lifecycleOwner = LocalLifecycleOwner.current
                                val lifecycleState by lifecycleOwner.lifecycle.currentStateFlow.collectAsState()

                                LaunchedEffect(lifecycleState){
                                    bleEnabled = mBluetoothAdapter.isEnabled
                                }

                                if (multiplePermissionsState.allPermissionsGranted) {

                                    if(bleEnabled) {

                                        MainScreen()

                                    } else {

                                        val context = LocalContext.current

                                        LaunchedEffect(mBluetoothAdapter.isEnabled){
                                            val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                                            (context as Activity).startActivityForResult(intent, 1)
                                        }
                                    }

                                } else {

                                    LaunchedEffect(multiplePermissionsState) {
                                        multiplePermissionsState.launchMultiplePermissionRequest()
                                    }

                                }

                            }

                        }

                    )

                }

            }

        }

    }

}

@Composable
fun Camera(){

    AndroidView(
        factory = {
            val cameraManager = it.getSystemService(CameraManager::class.java)

            cameraManager.cameraIdList.forEach {

                println("$it is front: ${cameraManager.getCameraCharacteristics(it).get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT}")

            }

            return@AndroidView SurfaceView(it)
        }
    )

}