package com.example.barokahstore

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
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.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.barokahstore.data.DatabaseHelper
import com.example.barokahstore.data.User
import com.example.barokahstore.theme.BarokahStoreTheme
import com.example.barokahstore.ui.screens.*
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

enum class AppScreen(val title: String, val icon: androidx.compose.ui.graphics.vector.ImageVector) {
    Dashboard("Dashboard", Icons.Default.Home),
    Kasir("Kasir", Icons.Default.ShoppingCart),
    Stok("Stok Barang", Icons.Default.List),
    Piutang("Piutang", Icons.Default.Star),
    History("Riwayat Sales", Icons.Default.Refresh),
    Absensi("Absensi", Icons.Default.AccountBox),
    Laporan("Laporan", Icons.Default.Menu),
    Pengaturan("Pengaturan", Icons.Default.Settings)
}

class MainActivity : ComponentActivity() {
    private lateinit var dbHelper: DatabaseHelper

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        dbHelper = DatabaseHelper.getInstance(this)

        enableEdgeToEdge()
        setContent {
            BarokahStoreTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    AppMainLayout(dbHelper)
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AppMainLayout(dbHelper: DatabaseHelper) {
    var currentUser by remember { mutableStateOf<User?>(null) }
    val screenBackStack = remember { mutableStateListOf(AppScreen.Dashboard) }
    val currentScreen = screenBackStack.lastOrNull() ?: AppScreen.Dashboard

    if (currentUser == null) {
        LoginScreen(
            dbHelper = dbHelper,
            onLoginSuccess = { user ->
                currentUser = user
                screenBackStack.clear()
                screenBackStack.add(AppScreen.Dashboard)
            }
        )
    } else {
        val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
        val scope = rememberCoroutineScope()
        
        // Handle Back button
        BackHandler(enabled = drawerState.isOpen || screenBackStack.size > 1) {
            if (drawerState.isOpen) {
                scope.launch { drawerState.close() }
            } else {
                screenBackStack.removeLastOrNull()
            }
        }
        val settings = remember { dbHelper.getSettings() }
        val todayDateStr = remember { SimpleDateFormat("dd MMM YYYY", Locale.getDefault()).format(Date()) }

        val isAdmin = currentUser!!.role == "admin"
        
        // Filter sidebar menus based on role
        val menuItems = AppScreen.values().filter { screen ->
            when (screen) {
                AppScreen.Absensi, AppScreen.Laporan, AppScreen.Pengaturan -> isAdmin
                else -> true
            }
        }

        ModalNavigationDrawer(
            drawerState = drawerState,
            drawerContent = {
                ModalDrawerSheet(
                    drawerContainerColor = Color(0xFFF9FAFB),
                    modifier = Modifier.width(280.dp)
                ) {
                    // Header Brand
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .background(Color(0xFF4F46E5))
                            .padding(24.dp)
                            .padding(top = 16.dp)
                    ) {
                        Column {
                            Row(verticalAlignment = Alignment.CenterVertically) {
                                Icon(
                                    imageVector = Icons.Default.Home,
                                    contentDescription = null,
                                    tint = Color.White,
                                    modifier = Modifier.size(28.dp)
                                )
                                Spacer(modifier = Modifier.width(10.dp))
                                Text(
                                    text = settings.storeName,
                                    color = Color.White,
                                    fontSize = 20.sp,
                                    fontWeight = FontWeight.Bold
                                )
                            }
                        }
                    }

                    // Profile Summary Card
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp)
                            .background(Color.White, RoundedCornerShape(12.dp))
                            .padding(12.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Surface(
                            shape = CircleShape,
                            color = Color(0xFFE0E7FF),
                            modifier = Modifier.size(45.dp)
                        ) {
                            Box(contentAlignment = Alignment.Center) {
                                Text(
                                    text = currentUser!!.name.take(1).uppercase(),
                                    color = Color(0xFF4F46E5),
                                    fontSize = 20.sp,
                                    fontWeight = FontWeight.Bold
                                )
                            }
                        }
                        Spacer(modifier = Modifier.width(12.dp))
                        Column {
                            Text(
                                text = currentUser!!.name,
                                fontWeight = FontWeight.Bold,
                                fontSize = 14.sp,
                                color = Color(0xFF1F2937)
                            )
                            Text(
                                text = currentUser!!.role.uppercase(),
                                fontSize = 11.sp,
                                color = Color.Gray,
                                fontWeight = FontWeight.Medium
                            )
                        }
                    }

                    Divider(color = Color(0xFFE5E7EB), modifier = Modifier.padding(horizontal = 16.dp))

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

                    // Menu items list
                    LazyColumn(
                        modifier = Modifier
                            .weight(1f)
                            .padding(horizontal = 12.dp),
                        verticalArrangement = Arrangement.spacedBy(4.dp)
                    ) {
                        items(menuItems) { screen ->
                            val isSelected = currentScreen == screen
                            NavigationDrawerItem(
                                label = { Text(screen.title, fontWeight = FontWeight.Bold) },
                                icon = {
                                    Icon(
                                        imageVector = screen.icon,
                                        contentDescription = null,
                                        tint = if (isSelected) Color(0xFF4F46E5) else Color.Gray
                                    )
                                },
                                selected = isSelected,
                                onClick = {
                                    if (screenBackStack.lastOrNull() != screen) {
                                        screenBackStack.add(screen)
                                    }
                                    scope.launch { drawerState.close() }
                                },
                                colors = NavigationDrawerItemDefaults.colors(
                                    selectedContainerColor = Color(0xFFEEF2FF),
                                    selectedTextColor = Color(0xFF4F46E5),
                                    unselectedTextColor = Color(0xFF4B5563)
                                ),
                                shape = RoundedCornerShape(10.dp)
                            )
                        }
                    }

                    Divider(color = Color(0xFFE5E7EB), modifier = Modifier.padding(horizontal = 16.dp))

                    // Logout Action
                    NavigationDrawerItem(
                        label = { Text("Keluar", color = Color(0xFFDC2626), fontWeight = FontWeight.Bold) },
                        icon = {
                            Icon(
                                imageVector = Icons.Default.ExitToApp,
                                contentDescription = "Keluar",
                                tint = Color(0xFFDC2626)
                            )
                        },
                        selected = false,
                        onClick = {
                            currentUser?.let { user ->
                                dbHelper.checkOutUser(user.id)
                            }
                            currentUser = null
                            scope.launch { drawerState.close() }
                        },
                        shape = RoundedCornerShape(10.dp),
                        modifier = Modifier.padding(12.dp)
                    )
                }
            }
        ) {
            Scaffold(
                topBar = {
                    TopAppBar(
                        title = {
                            Text(
                                text = currentScreen.title,
                                fontWeight = FontWeight.Bold,
                                fontSize = 18.sp,
                                color = Color(0xFF1F2937)
                            )
                        },
                        navigationIcon = {
                            IconButton(onClick = { scope.launch { drawerState.open() } }) {
                                Icon(Icons.Default.Menu, contentDescription = "Menu")
                            }
                        },
                        actions = {
                            // Store badge / date indicator
                            Row(
                                modifier = Modifier
                                    .padding(end = 12.dp)
                                    .background(Color(0xFFF3F4F6), RoundedCornerShape(8.dp))
                                    .padding(horizontal = 8.dp, vertical = 4.dp),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Icon(
                                    imageVector = Icons.Default.Check,
                                    contentDescription = null,
                                    tint = Color(0xFF059669),
                                    modifier = Modifier.size(14.dp)
                                )
                                Spacer(modifier = Modifier.width(4.dp))
                                Text(
                                    text = settings.storeName,
                                    fontSize = 11.sp,
                                    fontWeight = FontWeight.Bold,
                                    color = Color(0xFF374151)
                                )
                                Spacer(modifier = Modifier.width(8.dp))
                                Text(
                                    text = todayDateStr,
                                    fontSize = 10.sp,
                                    color = Color.Gray
                                )
                            }
                        },
                        colors = TopAppBarDefaults.topAppBarColors(
                            containerColor = Color.White,
                            navigationIconContentColor = Color(0xFF1F2937)
                        )
                    )
                }
            ) { paddingValues ->
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues)
                        .background(Color(0xFFF3F4F6))
                ) {
                    when (currentScreen) {
                        AppScreen.Dashboard -> DashboardScreen(
                            dbHelper = dbHelper,
                            currentUser = currentUser!!,
                            onNavigateTo = { target ->
                                when (target) {
                                    "stok" -> {
                                        if (screenBackStack.lastOrNull() != AppScreen.Stok) {
                                            screenBackStack.add(AppScreen.Stok)
                                        }
                                    }
                                    "riwayat" -> {
                                        if (screenBackStack.lastOrNull() != AppScreen.History) {
                                            screenBackStack.add(AppScreen.History)
                                        }
                                    }
                                }
                            }
                        )
                        AppScreen.Kasir -> KasirScreen(
                            dbHelper = dbHelper,
                            currentUser = currentUser!!
                        )
                        AppScreen.Stok -> StokScreen(
                            dbHelper = dbHelper,
                            currentUser = currentUser!!
                        )
                        AppScreen.Piutang -> PiutangScreen(
                            dbHelper = dbHelper,
                            currentUser = currentUser!!
                        )
                        AppScreen.History -> HistoryScreen(
                            dbHelper = dbHelper,
                            currentUser = currentUser!!
                        )
                        AppScreen.Absensi -> AbsensiScreen(
                            dbHelper = dbHelper,
                            currentUser = currentUser!!
                        )

                        AppScreen.Laporan -> LaporanScreen(
                            dbHelper = dbHelper,
                            currentUser = currentUser!!
                        )
                        AppScreen.Pengaturan -> PengaturanScreen(
                            dbHelper = dbHelper,
                            currentUser = currentUser!!
                        )
                    }
                }
            }
        }
    }
}
