package com.sample.tabs.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.tabs.kotlin.ui.components.FullScreenWebView
import com.sample.tabs.kotlin.ui.components.SplashScreen
import com.sample.tabs.kotlin.ui.theme.TabsAppTheme
import com.sample.tabs.kotlin.utils.NetworkMonitor

class MainActivity : ComponentActivity() {

    // Configuration for tab state preservation
    private val preserveTabState = {{.preserve_tab_state}}

    // Storage for tab states and URLs
    private val tabStates = mutableMapOf<Int, Bundle>()
    private val tabUrls = mutableMapOf<Int, String>()
    private val tabWebViews = mutableMapOf<Int, WebView?>()

    private val permissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        // Permissions granted, WebView will handle them
    }

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

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

        // Request permissions
        requestPermissions()

        setContent {
            TabsAppTheme {
                ContentApp()
            }
        }
    }

    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 TabItem(val route: String, val label: String, val icon: ImageVector) {
    object Home : TabItem("home", "Home", Icons.Default.Home)
    object About : TabItem("about", "About", Icons.Default.Info)
    object Settings : TabItem("settings", "Settings", Icons.Default.Settings)
}

@Composable
fun ContentApp() {
    val context = LocalContext.current
    val networkMonitor = remember { NetworkMonitor(context) }
    val isConnected by networkMonitor.isConnected.collectAsState(initial = networkMonitor.checkCurrentConnectivity())

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

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainActivity.TabsApp(isConnected: Boolean) {
    var selectedTab by remember { mutableIntStateOf(0) }
    var previousTab by remember { mutableIntStateOf(0) }
    var pageTitle by remember { mutableStateOf<String?>(null) }
    val tabs = listOf(TabItem.Home, TabItem.About, TabItem.Settings)

    // Save state when tab changes (if preservation is enabled)
    LaunchedEffect(selectedTab) {
        if (preserveTabState && selectedTab != previousTab) {
            // Save previous tab's state
            tabWebViews[previousTab]?.let { webView ->
                val bundle = Bundle()
                webView.saveState(bundle)
                tabStates[previousTab] = bundle
                tabUrls[previousTab] = webView.url ?: ""
            }
            previousTab = selectedTab
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        text = if (selectedTab == 0) {
                            pageTitle?.takeIf { it.isNotBlank() } ?: "Tabs App"
                        } else {
                            tabs[selectedTab].label
                        },
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer
                )
            )
        },
        bottomBar = {
            NavigationBar {
                tabs.forEachIndexed { index, tab ->
                    NavigationBarItem(
                        icon = { Icon(tab.icon, contentDescription = null) },
                        label = { Text(tab.label) },
                        selected = selectedTab == index,
                        onClick = { selectedTab = index }
                    )
                }
            }
        },
        contentWindowInsets = WindowInsets(0, 0, 0, 0)
    ) { paddingValues ->
        Box(modifier = Modifier.padding(paddingValues)) {
            when (selectedTab) {
                0 -> FullScreenWebView(
                    url = if (preserveTabState && tabUrls.containsKey(0)) {
                        tabUrls[0] ?: "https://example.com"
                    } else {
                        "https://example.com"
                    },
                    isConnected = isConnected,
                    savedState = if (preserveTabState) tabStates[0] else null,
                    onTitleReceived = { title -> pageTitle = title },
                    onWebViewCreated = { webView -> tabWebViews[0] = webView }
                )
                1 -> AboutScreen()
                2 -> SettingsScreen()
            }
        }
    }
}

@Composable
fun AboutScreen() {
    Column(
        modifier = Modifier.fillMaxSize().padding(16.dp),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text("Tabs App", style = MaterialTheme.typography.headlineMedium)
        Spacer(modifier = Modifier.height(8.dp))
        Text("Native Kotlin Android app with bottom navigation tabs 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: Tabs")
    }
}
