package eu.darken.bluemusic.devices.ui.dashboard

import android.content.Intent
import android.provider.Settings
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.BluetoothDisabled
import androidx.compose.material.icons.twotone.Add
import androidx.compose.material.icons.twotone.Bluetooth
import androidx.compose.material.icons.twotone.BluetoothConnected
import androidx.compose.material.icons.twotone.Lock
import androidx.compose.material.icons.twotone.Settings
import androidx.compose.material.icons.twotone.Stars
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.TopAppBarScrollBehavior
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import eu.darken.bluemusic.R
import eu.darken.bluemusic.bluetooth.core.MockDevice
import eu.darken.bluemusic.bluetooth.core.SourceDevice
import eu.darken.bluemusic.common.compose.Preview2
import eu.darken.bluemusic.common.compose.PreviewWrapper
import eu.darken.bluemusic.common.compose.horizontalCutoutPadding
import eu.darken.bluemusic.common.compose.navigationBarBottomPadding
import eu.darken.bluemusic.common.debug.logging.Logging.Priority.INFO
import eu.darken.bluemusic.common.debug.logging.log
import eu.darken.bluemusic.common.debug.logging.logTag
import eu.darken.bluemusic.common.navigation.Nav
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.darken.bluemusic.devices.core.DeviceAddr
import eu.darken.bluemusic.devices.ui.dashboard.rows.Android10AppLaunchHintCard
import eu.darken.bluemusic.devices.ui.dashboard.rows.BatteryOptimizationHintCard
import eu.darken.bluemusic.devices.ui.dashboard.rows.DeviceSpeakerHintCard
import eu.darken.bluemusic.devices.ui.dashboard.rows.DndAccessHintCard
import eu.darken.bluemusic.devices.ui.dashboard.rows.EmptyDevicesCard
import eu.darken.bluemusic.devices.ui.dashboard.rows.NotificationPermissionHintCard
import eu.darken.bluemusic.devices.ui.dashboard.rows.ReviewCard
import eu.darken.bluemusic.devices.ui.dashboard.rows.device.ManagedDeviceItem
import eu.darken.bluemusic.upgrade.ui.brandTitleTwoTone

@Composable
fun DevicesScreenHost(vm: DashboardViewModel = hiltViewModel()) {

    val state by vm.state.collectAsStateWithLifecycle()

    val activity = LocalContext.current as? android.app.Activity

    val permissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        log(vm.tag, INFO) { "Permission granted: $isGranted" }
    }

    LaunchedEffect(Unit) {
        vm.events.collect { event ->
            when (event) {
                is DashboardEvent.RequestPermission -> {
                    permissionLauncher.launch(event.permission)
                }
            }
        }
    }

    state?.let { state ->
        DevicesScreen(
            state = state,
            onAddDevice = { vm.navTo(Nav.Main.DiscoverDevices) },
            onDeviceConfig = { vm.navTo(Nav.Main.DeviceConfig(it)) },
            onDeviceAction = { vm.action(it) },
            onNavigateToSettings = { vm.navTo(Nav.Main.SettingsIndex) },
            onNavigateToUpgrade = { vm.onUpgradeClicked() },
            onRequestBluetoothPermission = {
                vm.action(DashboardAction.RequestBluetoothPermission)
            },
            onReview = activity?.let { { vm.reviewNow(it) } },
            onReviewDismiss = { vm.reviewDismiss() },
        )
    }
}

@Composable
fun DevicesScreen(
    state: DashboardViewModel.State,
    onAddDevice: () -> Unit,
    onDeviceConfig: (addr: DeviceAddr) -> Unit,
    onDeviceAction: (DashboardAction) -> Unit,
    onNavigateToSettings: () -> Unit,
    onNavigateToUpgrade: () -> Unit,
    onRequestBluetoothPermission: () -> Unit,
    onReview: (() -> Unit)? = null,
    onReviewDismiss: () -> Unit = {},
) {
    val listState = rememberLazyListState()
    val isScrolledDown by remember {
        derivedStateOf {
            listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 0
        }
    }
    val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior()

    Scaffold(
        modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
        topBar = {
            ManagedDevicesTopBar(
                scrollBehavior = scrollBehavior,
                isProVersion = state.isProVersion,
                isBluetoothEnabled = state.isBluetoothEnabled,
                hasBluetoothPermission = state.hasBluetoothPermission,
                hasConnectedDevice = state.devicesWithApps.any {
                    it.device.type != SourceDevice.Type.PHONE_SPEAKER && it.device.isConnected
                },
                onNavigateToSettings = onNavigateToSettings,
                onNavigateToUpgrade = onNavigateToUpgrade
            )
        },
        contentWindowInsets = WindowInsets.statusBars,
        floatingActionButton = {
            AnimatedVisibility(
                visible = !isScrolledDown && state.hasBluetoothPermission && state.isBluetoothEnabled && state.devicesWithApps.isNotEmpty(),
                enter = slideInVertically(initialOffsetY = { it * 2 }),
                exit = slideOutVertically(targetOffsetY = { it * 2 })
            ) {
                FloatingActionButton(
                    onClick = { onAddDevice() },
                    containerColor = MaterialTheme.colorScheme.primary,
                    modifier = Modifier.navigationBarsPadding()
                ) {
                    Icon(
                        imageVector = Icons.TwoTone.Add,
                        contentDescription = stringResource(R.string.label_add_device)
                    )
                }
            }
        }
    ) { paddingValues ->
        val navBarPadding = navigationBarBottomPadding()
        LazyColumn(
            state = listState,
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .horizontalCutoutPadding(),
            contentPadding = PaddingValues(top = 8.dp, bottom = 8.dp + navBarPadding)
        ) {
            // Critical permission/state cards - these block normal functionality
            if (!state.hasBluetoothPermission) {
                item {
                    BluetoothPermissionCard(
                        onRequestPermission = onRequestBluetoothPermission
                    )
                }
            }

            if (state.hasBluetoothPermission && !state.isBluetoothEnabled) {
                item {
                    BluetoothDisabledCard()
                }
            }

            if (state.showBatteryOptimizationHint && state.batteryOptimizationIntent != null) {
                item {
                    BatteryOptimizationHintCard(
                        intent = state.batteryOptimizationIntent,
                        onDismiss = { onDeviceAction(DashboardAction.DismissBatteryOptimizationHint) }
                    )
                }
            }

            if (state.showAndroid10AppLaunchHint && state.android10AppLaunchIntent != null) {
                item {
                    Android10AppLaunchHintCard(
                        intent = state.android10AppLaunchIntent,
                        onDismiss = { onDeviceAction(DashboardAction.DismissAndroid10AppLaunchHint) }
                    )
                }
            }

            if (state.showDndAccessHint && state.dndAccessIntent != null) {
                item {
                    DndAccessHintCard(
                        intent = state.dndAccessIntent,
                        onDismiss = { onDeviceAction(DashboardAction.DismissDndAccessHint) }
                    )
                }
            }

            if (state.showNotificationPermissionHint) {
                item {
                    NotificationPermissionHintCard(
                        onRequestPermission = { onDeviceAction(DashboardAction.RequestNotificationPermission) },
                        onDismiss = { onDeviceAction(DashboardAction.DismissNotificationPermissionHint) }
                    )
                }
            }

            if (state.showSpeakerHint) {
                item {
                    DeviceSpeakerHintCard(
                        onDismiss = { onDeviceAction(DashboardAction.DismissSpeakerHint) },
                        onAdd = { onDeviceAction(DashboardAction.AddSpeakerDevice) }
                    )
                }
            }

            if (state.showReviewCard) {
                item {
                    ReviewCard(
                        onReview = onReview,
                        onDismiss = onReviewDismiss
                    )
                }
            }

            if (state.hasBluetoothPermission && state.isBluetoothEnabled) {
                if (state.devicesWithApps.isEmpty() && !state.isLoading) {
                    item {
                        EmptyDevicesCard(onAddDevice = onAddDevice)
                    }
                } else {
                    items(
                        items = state.devicesWithApps,
                        key = { it.device.address }
                    ) { deviceWithApps ->
                        ManagedDeviceItem(
                            device = deviceWithApps.device,
                            launchApps = deviceWithApps.launchApps,
                            onDeviceAction = onDeviceAction,
                            onNavigateToConfig = { onDeviceConfig(deviceWithApps.device.address) },
                            isOnlyDevice = state.devicesWithApps.size == 1,
                            isLocked = deviceWithApps.device.address in state.lockedDevices,
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun ManagedDevicesTopBar(
    scrollBehavior: TopAppBarScrollBehavior,
    isProVersion: Boolean,
    isBluetoothEnabled: Boolean,
    hasBluetoothPermission: Boolean,
    hasConnectedDevice: Boolean,
    onNavigateToSettings: () -> Unit,
    onNavigateToUpgrade: () -> Unit
) {
    val context = LocalContext.current

    TopAppBar(
        scrollBehavior = scrollBehavior,
        title = {
            if (isProVersion) {
                Text(
                    text = brandTitleTwoTone(),
                    style = MaterialTheme.typography.headlineSmall,
                )
            } else {
                Text(text = stringResource(R.string.app_name_short))
            }
        },
        actions = {
            IconButton(onClick = {
                try {
                    val intent = Intent(Settings.ACTION_BLUETOOTH_SETTINGS)
                    context.startActivity(intent)
                } catch (e: Exception) {
                    log(TAG) { "Failed to open Bluetooth settings: $e" }
                    try {
                        val fallback = Intent(Settings.ACTION_SETTINGS)
                        context.startActivity(fallback)
                    } catch (e2: Exception) {
                        log(TAG) { "Failed to open general settings: $e2" }
                        Toast.makeText(
                            context,
                            R.string.general_error_no_compatible_app_found_msg,
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            }) {
                val isBluetoothReady = isBluetoothEnabled && hasBluetoothPermission
                Icon(
                    imageVector = when {
                        !isBluetoothReady -> Icons.Filled.BluetoothDisabled
                        hasConnectedDevice -> Icons.TwoTone.BluetoothConnected
                        else -> Icons.TwoTone.Bluetooth
                    },
                    contentDescription = stringResource(R.string.label_bluetooth_settings),
                    tint = if (isBluetoothReady && hasConnectedDevice) {
                        MaterialTheme.colorScheme.primary
                    } else {
                        MaterialTheme.colorScheme.onSurface
                    }
                )
            }
            if (!isProVersion) {
                IconButton(onClick = onNavigateToUpgrade) {
                    Icon(
                        imageVector = Icons.TwoTone.Stars,
                        contentDescription = stringResource(R.string.general_upgrade_action)
                    )
                }
            }
            IconButton(onClick = onNavigateToSettings) {
                Icon(
                    imageVector = Icons.TwoTone.Settings,
                    contentDescription = stringResource(R.string.settings_label)
                )
            }
        }
    )
}

@Composable
private fun BluetoothDisabledCard() {
    val context = LocalContext.current

    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.errorContainer
        )
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Icon(
                imageVector = Icons.Filled.BluetoothDisabled,
                contentDescription = null,
                modifier = Modifier.size(48.dp),
                tint = MaterialTheme.colorScheme.onErrorContainer
            )
            Spacer(modifier = Modifier.height(12.dp))
            Text(
                text = stringResource(R.string.title_bluetooth_is_off),
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.onErrorContainer
            )
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = stringResource(R.string.description_bluetooth_is_disabled),
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onErrorContainer,
                textAlign = TextAlign.Center
            )
            Spacer(modifier = Modifier.height(16.dp))
            Button(
                onClick = {
                    try {
                        val intent = Intent(Settings.ACTION_BLUETOOTH_SETTINGS)
                        context.startActivity(intent)
                    } catch (e: Exception) {
                        log(TAG) { "Failed to open Bluetooth settings: $e" }
                        try {
                            val fallback = Intent(Settings.ACTION_SETTINGS)
                            context.startActivity(fallback)
                        } catch (e2: Exception) {
                            log(TAG) { "Failed to open general settings: $e2" }
                            Toast.makeText(
                                context,
                                R.string.general_error_no_compatible_app_found_msg,
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                    }
                },
                colors = androidx.compose.material3.ButtonDefaults.buttonColors(
                    containerColor = MaterialTheme.colorScheme.error
                )
            ) {
                Text(stringResource(R.string.action_enable_bluetooth))
            }
        }
    }
}

@Composable
private fun BluetoothPermissionCard(
    onRequestPermission: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.errorContainer
        )
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Icon(
                imageVector = Icons.TwoTone.Lock,
                contentDescription = null,
                modifier = Modifier.size(48.dp),
                tint = MaterialTheme.colorScheme.onErrorContainer
            )
            Spacer(modifier = Modifier.height(12.dp))
            Text(
                text = stringResource(R.string.title_bluetooth_permission_required),
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.onErrorContainer
            )
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = stringResource(R.string.description_bluetooth_permission_required),
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onErrorContainer,
                textAlign = TextAlign.Center
            )
            Spacer(modifier = Modifier.height(16.dp))
            Button(
                onClick = onRequestPermission,
                colors = androidx.compose.material3.ButtonDefaults.buttonColors(
                    containerColor = MaterialTheme.colorScheme.error
                )
            ) {
                Text(stringResource(R.string.action_grant_permission))
            }
        }
    }
}


@Preview2
@Composable
private fun DevicesScreenPreview() {
    val devices = listOf(
        MockDevice().toManagedDevice(isConnected = true),
        MockDevice().toManagedDevice(),
    )

    PreviewWrapper {
        DevicesScreen(
            state = DashboardViewModel.State(
                devicesWithApps = devices.map { DashboardViewModel.DeviceWithApps(it, emptyList()) },
                isBluetoothEnabled = true,
                isProVersion = false,
            ),
            onAddDevice = {},
            onDeviceConfig = {},
            onDeviceAction = {},
            onNavigateToSettings = {},
            onNavigateToUpgrade = {},
            onRequestBluetoothPermission = {},
        )
    }
}

@Preview2
@Composable
private fun DevicesScreenSpeakerHintPreview() {
    val devices = listOf(MockDevice().toManagedDevice(isConnected = true))

    PreviewWrapper {
        DevicesScreen(
            state = DashboardViewModel.State(
                devicesWithApps = devices.map { DashboardViewModel.DeviceWithApps(it, emptyList()) },
                isBluetoothEnabled = true,
                isProVersion = false,
                showSpeakerHint = true,
            ),
            onAddDevice = {},
            onDeviceConfig = {},
            onDeviceAction = {},
            onNavigateToSettings = {},
            onNavigateToUpgrade = {},
            onRequestBluetoothPermission = {},
        )
    }
}

@Preview2
@Composable
private fun DevicesScreenEmptyPreview() {
    PreviewWrapper {
        DevicesScreen(
            state = DashboardViewModel.State(
                devicesWithApps = emptyList(),
                isBluetoothEnabled = true,
                isProVersion = true,
            ),
            onAddDevice = {},
            onDeviceConfig = {},
            onDeviceAction = {},
            onNavigateToSettings = {},
            onNavigateToUpgrade = {},
            onRequestBluetoothPermission = {},
        )
    }
}

@Preview2
@Composable
private fun ManagedDevicesScreenPermissionPreview() {
    PreviewWrapper {
        DevicesScreen(
            state = DashboardViewModel.State(
                devicesWithApps = emptyList(),
                isBluetoothEnabled = false,
                isProVersion = true,
            ),
            onAddDevice = {},
            onDeviceConfig = {},
            onDeviceAction = {},
            onNavigateToSettings = {},
            onNavigateToUpgrade = {},
            onRequestBluetoothPermission = {},
        )
    }
}

private val TAG = logTag("Dashboard", "Screen")
