package com.sample.drawer.kotlin

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import com.sample.drawer.kotlin.ui.components.FullScreenWebView
import com.sample.drawer.kotlin.ui.components.SplashScreen
import com.sample.drawer.kotlin.ui.theme.DrawerAppTheme
import com.sample.drawer.kotlin.utils.NetworkMonitor
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
    // Configuration for drawer item state preservation
    private val preserveTabState = {{.preserve_tab_state}}

    // Storage for drawer item states and URLs
    private val itemStates = mutableMapOf<Int, Bundle>()
    private val itemUrls = mutableMapOf<Int, String>()
    private val itemWebViews = mutableMapOf<Int, WebView?>()

    private val permissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Enable edge-to-edge display
        enableEdgeToEdge()

        requestPermissions()
        setContent {
            DrawerAppTheme {
                DrawerApp()
            }
        }
    }

    private fun requestPermissions() {
        val permissions = mutableListOf<String>()
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) permissions.add(Manifest.permission.CAMERA)
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) permissions.add(Manifest.permission.ACCESS_FINE_LOCATION)
        if (android.os.Build.VERSION.SDK_INT >= 33) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.READ_MEDIA_IMAGES)
                permissions.add(Manifest.permission.READ_MEDIA_VIDEO)
            }
        } else {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE)
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            }
        }
        if (permissions.isNotEmpty()) permissionLauncher.launch(permissions.toTypedArray())
    }
}

sealed class DrawerItem(val route: String, val label: String, val icon: ImageVector) {
    object Home : DrawerItem("home", "Home", Icons.Default.Home)
    object About : DrawerItem("about", "About", Icons.Default.Info)
    object Settings : DrawerItem("settings", "Settings", Icons.Default.Settings)
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainActivity.DrawerApp() {
    val context = LocalContext.current
    val networkMonitor = remember { NetworkMonitor(context) }
    val isConnected by networkMonitor.isConnected.collectAsState(initial = networkMonitor.checkCurrentConnectivity())

    if (!isConnected) {
        SplashScreen(
            isConnected = isConnected,
            onRetry = {
                // Connectivity state will update automatically via NetworkMonitor
            }
        )
        return
    }

    val drawerState = rememberDrawerState(DrawerValue.Closed)
    val scope = rememberCoroutineScope()
    var selectedItem by remember { mutableIntStateOf(0) }
    var previousItem by remember { mutableIntStateOf(0) }
    var pageTitle by remember { mutableStateOf<String?>(null) }
    val items = listOf(DrawerItem.Home, DrawerItem.About, DrawerItem.Settings)

    // Save state when drawer item changes (if preservation is enabled)
    LaunchedEffect(selectedItem) {
        if (preserveTabState && selectedItem != previousItem) {
            // Save previous item's state
            itemWebViews[previousItem]?.let { webView ->
                val bundle = Bundle()
                webView.saveState(bundle)
                itemStates[previousItem] = bundle
                itemUrls[previousItem] = webView.url ?: ""
            }
            previousItem = selectedItem
        }
    }

    ModalNavigationDrawer(
        drawerState = drawerState,
        drawerContent = {
            ModalDrawerSheet {
                Spacer(Modifier.height(12.dp))
                Text("Drawer App", modifier = Modifier.padding(16.dp), style = MaterialTheme.typography.titleLarge)
                items.forEachIndexed { index, item ->
                    NavigationDrawerItem(
                        icon = { Icon(item.icon, contentDescription = null) },
                        label = { Text(item.label) },
                        selected = selectedItem == index,
                        onClick = {
                            scope.launch { drawerState.close() }
                            selectedItem = index
                        },
                        modifier = Modifier.padding(horizontal = 12.dp)
                    )
                }
            }
        }
    ) {
        Scaffold(
            topBar = {
                TopAppBar(
                    title = {
                        Text(
                            text = if (selectedItem == 0) {
                                pageTitle?.takeIf { it.isNotBlank() } ?: "Drawer App"
                            } else {
                                items[selectedItem].label
                            },
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis
                        )
                    },
                    navigationIcon = {
                        IconButton(onClick = { scope.launch { drawerState.open() } }) {
                            Icon(Icons.Default.Menu, contentDescription = "Menu")
                        }
                    },
                    colors = TopAppBarDefaults.topAppBarColors(
                        containerColor = MaterialTheme.colorScheme.primaryContainer,
                        titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer
                    )
                )
            },
            contentWindowInsets = WindowInsets(0, 0, 0, 0)
        ) { paddingValues ->
            Box(modifier = Modifier.padding(paddingValues)) {
                when (selectedItem) {
                    0 -> FullScreenWebView(
                        url = if (preserveTabState && itemUrls.containsKey(0)) {
                            itemUrls[0] ?: "https://example.com"
                        } else {
                            "https://example.com"
                        },
                        isConnected = isConnected,
                        savedState = if (preserveTabState) itemStates[0] else null,
                        onTitleReceived = { title -> pageTitle = title },
                        onWebViewCreated = { webView -> itemWebViews[0] = webView }
                    )
                    1 -> AboutScreen()
                    2 -> SettingsScreen()
                }
            }
        }
    }
}

@Composable
fun AboutScreen() {
    Column(modifier = Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
        Text("Drawer App", style = MaterialTheme.typography.headlineMedium)
        Spacer(modifier = Modifier.height(8.dp))
        Text("Native Kotlin Android app with navigation drawer and Material 3 design.")
    }
}

@Composable
fun SettingsScreen() {
    Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
        Text("Settings", style = MaterialTheme.typography.headlineMedium)
        Spacer(modifier = Modifier.height(16.dp))
        Text("App Version: 1.0")
        Text("Navigation Style: Drawer")
    }
}
