/*
 * Copyright (c) 2026 QPQ IaaS AG <info@qpq.swiss>. All rights reserved.
 * Project: Gajumaru Core Java Libraries <gajumaru.io>
 *
 * This program is dual-licensed:
 * 1) Under the GNU Affero General Public License as published by the Free
 *    Software Foundation, either version 3 of the License, or (at your option)
 *    any later version (AGPL-3.0-or-later).
 *
 * 2) Under a commercial/proprietary license available directly from QPQ IaaS AG.
 *    If you wish to use this software outside the strict constraints of the
 *    AGPLv3 (e.g. within a closed-source or proprietary product), you must
 *    purchase a commercial license from QPQ IaaS AG.
 *
 * Authors:
 *   - Craig Everett <craigeverett@qpq.swiss>
 *
 * SPDX-License-Identifier: AGPL-3.0-or-later OR LicenseRef-QPQ-Commercial
 */

package swiss.qpq.gajumobile.ui.screens

import android.content.ClipData
import android.content.Intent
import androidx.core.net.toUri
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SecondaryScrollableTabRow
import androidx.compose.material3.Surface
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRowDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.ClipEntry
import androidx.compose.ui.platform.LocalClipboard
import androidx.compose.ui.res.painterResource
import kotlin.time.Duration.Companion.seconds
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.launch
import swiss.qpq.gajumobile.R
import swiss.qpq.gajumobile.data.models.Wallet
import swiss.qpq.gajumaru.core.formatting.GajuFormat
import swiss.qpq.gajumobile.ui.components.ActionCircle
import swiss.qpq.gajumobile.ui.components.GajuTopBar

@Composable
fun DashboardScreen(
    wallets: List<Wallet>,
    selectedWalletIndex: Int,
    onWalletIndexChange: (Int) -> Unit,
    selectedAccountIndex: Int,
    onAccountIndexChange: (Int) -> Unit,
    balanceFormat: GajuFormat.Type = GajuFormat.Type.US,
    balanceUnit: GajuFormat.Unit = GajuFormat.Unit.GAJU,
    onSend: () -> Unit,
    onReceive: () -> Unit,
    onGrids: () -> Unit,
    onAddAccount: (String) -> Unit,
    onAccountSettings: (String, String) -> Unit,
    onRefresh: (String, String) -> Unit,
    onNavigate: (String) -> Unit,
) {
    val context = androidx.compose.ui.platform.LocalContext.current
    if (wallets.isEmpty()) {
        Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                Text(stringResource(R.string.no_wallets_message))
                Spacer(modifier = Modifier.height(16.dp))
                ActionCircle(
                    text = stringResource(R.string.create_button),
                    containerColor = MaterialTheme.colorScheme.primary,
                    contentColor = MaterialTheme.colorScheme.onPrimary,
                    onClick = { onNavigate("CREATE_WALLET") }
                )
                Spacer(modifier = Modifier.height(32.dp))
                Text(
                    text = stringResource(R.string.wallets_corrupted_message),
                    style = MaterialTheme.typography.labelSmall,
                    color = MaterialTheme.colorScheme.error,
                    textAlign = TextAlign.Center,
                    modifier = Modifier.padding(horizontal = 48.dp)
                )
                androidx.compose.material3.TextButton(
                    onClick = { onNavigate("WIPE_DATA") }
                ) {
                    Text(stringResource(R.string.wipe_broken_wallets_button), color = MaterialTheme.colorScheme.error)
                }
            }
        }
        return
    }

    val clipboard = LocalClipboard.current
    val scope = rememberCoroutineScope()
    val accountIdLabel = stringResource(R.string.account_id_label_clipboard)
    val walletPagerState = rememberPagerState(initialPage = selectedWalletIndex.coerceIn(0, wallets.size - 1)) { wallets.size }
    
    // Sync pager state back to router
    LaunchedEffect(walletPagerState.currentPage) {
        onWalletIndexChange(walletPagerState.currentPage)
    }

    val currentWallet = wallets[walletPagerState.currentPage]
    val currentAccount = currentWallet.accounts.getOrNull(selectedAccountIndex)

    // Automatically refresh balance after 1 second of staying on an account
    LaunchedEffect(currentAccount?.id) {
        currentAccount?.let { account ->
            kotlinx.coroutines.delay(1.seconds)
            onRefresh(currentWallet.id, account.id)
        }
    }

    Scaffold(
        topBar = { GajuTopBar(onNavigate = onNavigate) },
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(MaterialTheme.colorScheme.background)
                .padding(innerPadding),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
            // Wallet Area
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 8.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                HorizontalPager(
                    state = walletPagerState,
                    modifier = Modifier.fillMaxWidth().height(48.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) { page ->
                    Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                        Text(
                            text = wallets[page].name,
                            color = MaterialTheme.colorScheme.onBackground,
                            fontSize = 20.sp,
                            fontWeight = FontWeight.Bold,
                            textAlign = TextAlign.Center
                        )
                    }
                }
                
                // Pager Indicators
                Row(
                    Modifier.height(8.dp).fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center
                ) {
                    repeat(wallets.size) { iteration ->
                        val color = if (walletPagerState.currentPage == iteration) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surfaceVariant
                        Box(
                            modifier = Modifier
                                .padding(2.dp)
                                .background(color, androidx.compose.foundation.shape.CircleShape)
                                .size(6.dp)
                        )
                    }
                }
            }
            
            // Account Tabs
            if (currentWallet.accounts.isNotEmpty()) {
                Surface(
                    modifier = Modifier
                        .padding(horizontal = 16.dp, vertical = 8.dp)
                        .fillMaxWidth(),
                    color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f),
                    shape = RoundedCornerShape(12.dp)
                ) {
                    SecondaryScrollableTabRow(
                        selectedTabIndex = selectedAccountIndex,
                        containerColor = Color.Transparent,
                        contentColor = MaterialTheme.colorScheme.onBackground,
                        divider = {},
                        edgePadding = 12.dp,
                        indicator = {
                            TabRowDefaults.SecondaryIndicator(
                                modifier = Modifier.tabIndicatorOffset(selectedAccountIndex),
                                color = MaterialTheme.colorScheme.primary,
                            )
                        }
                    ) {
                        currentWallet.accounts.forEachIndexed { index, account ->
                            val isSelected = selectedAccountIndex == index
                            Tab(
                                selected = isSelected,
                                onClick = { onAccountIndexChange(index) },
                                text = { 
                                    Text(
                                        text = account.label, 
                                        color = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
                                        style = MaterialTheme.typography.labelMedium,
                                        fontWeight = FontWeight.Bold,
                                        maxLines = 1,
                                        overflow = TextOverflow.Ellipsis,
                                        modifier = Modifier.widthIn(max = 100.dp)
                                    ) 
                                }
                            )
                        }
                        
                        // Trailing "+" Tab to Add Account
                        Tab(
                            selected = false,
                            onClick = { onAddAccount(currentWallet.id) },
                            text = {
                                Icon(
                                    painter = painterResource(id = R.drawable.ic_add),
                                    contentDescription = stringResource(R.string.add_account_content_desc),
                                    tint = MaterialTheme.colorScheme.primary,
                                    modifier = Modifier.size(20.dp)
                                )
                            }
                        )
                    }
                }
            }

            // Account ID Display with Copy Widget
            currentAccount?.let { account ->
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 24.dp)
                        .padding(bottom = 12.dp),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = account.getShortId(),
                        style = MaterialTheme.typography.bodySmall.copy(
                            fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace
                        ),
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    IconButton(
                        onClick = { 
                            scope.launch {
                                clipboard.setClipEntry(ClipEntry(ClipData.newPlainText(accountIdLabel, account.gajuId)))
                            }
                        },
                        modifier = Modifier.size(24.dp)
                    ) {
                        Icon(
                            painter = painterResource(id = R.drawable.ic_content_copy), 
                            contentDescription = stringResource(R.string.copy_id_content_desc),
                            tint = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.size(16.dp)
                        )
                    }
                }
                
                // View on Explorer Link
                androidx.compose.material3.TextButton(
                    onClick = {
                        val url = "https://${currentWallet.networkId}.gajumaru.io/account/${account.gajuId}"
                        val intent = Intent(Intent.ACTION_VIEW, url.toUri())
                        context.startActivity(intent)
                    },
                    modifier = Modifier.padding(bottom = 12.dp)
                ) {
                    Text(
                        text = stringResource(R.string.view_account_in_explorer),
                        style = MaterialTheme.typography.labelMedium,
                        color = MaterialTheme.colorScheme.primary,
                        fontWeight = FontWeight.Bold
                    )
                }
            }
            
            // Balance Box
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 24.dp)
                    .background(MaterialTheme.colorScheme.surfaceVariant, RoundedCornerShape(16.dp))
                    .padding(24.dp),
            ) {
                Column {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        Column {
                            Text(stringResource(R.string.balance_label), color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 14.sp)
                            Text(
                                text = stringResource(R.string.on_network_label, currentWallet.networkId.uppercase()),
                                style = MaterialTheme.typography.labelSmall,
                                color = MaterialTheme.colorScheme.primary.copy(alpha = 0.8f),
                                fontWeight = FontWeight.Bold
                            )
                        }
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            IconButton(
                                onClick = { 
                                    currentAccount?.let { onRefresh(currentWallet.id, it.id) }
                                },
                                modifier = Modifier.size(24.dp)
                            ) {
                                Icon(
                                    painter = painterResource(id = R.drawable.ic_refresh),
                                    contentDescription = stringResource(R.string.refresh_balance_content_desc),
                                    tint = MaterialTheme.colorScheme.onSurfaceVariant,
                                    modifier = Modifier.size(20.dp),
                                )
                            }
                            Spacer(modifier = Modifier.width(8.dp))
                            IconButton(
                                onClick = { 
                                    currentAccount?.let { onAccountSettings(currentWallet.id, it.id) }
                                },
                                modifier = Modifier.size(24.dp)
                            ) {
                                Icon(
                                    painter = painterResource(id = R.drawable.settings), 
                                    contentDescription = stringResource(R.string.account_settings_content_desc),
                                    tint = MaterialTheme.colorScheme.onSurfaceVariant,
                                    modifier = Modifier.size(24.dp),
                                )
                            }
                        }
                    }
                    
                    Spacer(modifier = Modifier.height(16.dp))
                    
                    val balanceStr = currentAccount?.formattedBalance(balanceFormat, balanceUnit) ?: "0"

                    Text(
                        text = balanceStr,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        fontSize = 24.sp,
                        fontWeight = FontWeight.Bold,
                    )
                    
                    currentAccount?.cachedBalance?.let { balance ->
                        val timeStr = remember(balance.timestamp) {
                            val instant = java.time.Instant.ofEpochMilli(balance.timestamp)
                            val dateTime = java.time.LocalDateTime.ofInstant(instant, java.time.ZoneId.systemDefault())
                            dateTime.format(java.time.format.DateTimeFormatter.ofPattern("HH:mm:ss"))
                        }
                        Text(
                            text = stringResource(R.string.last_balance_check_label, timeStr),
                            style = MaterialTheme.typography.labelSmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f),
                            modifier = Modifier.padding(top = 4.dp)
                        )
                    }
                }
            }
            
            Spacer(modifier = Modifier.weight(1f))
            
            // Send / Receive / GRIDS Buttons
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 64.dp),
                horizontalArrangement = Arrangement.SpaceEvenly,
            ) {
                ActionCircle(
                    text = stringResource(R.string.send_action),
                    containerColor = MaterialTheme.colorScheme.tertiary,
                    contentColor = MaterialTheme.colorScheme.onTertiary,
                    onClick = onSend,
                )
                ActionCircle(
                    text = stringResource(R.string.grids_action),
                    containerColor = MaterialTheme.colorScheme.tertiary,
                    contentColor = MaterialTheme.colorScheme.onTertiary,
                    onClick = onGrids,
                )
                ActionCircle(
                    text = stringResource(R.string.receive_action),
                    containerColor = MaterialTheme.colorScheme.tertiary,
                    contentColor = MaterialTheme.colorScheme.onTertiary,
                    onClick = onReceive,
                )
            }
        }
    }
}
