package com.aegir.demo.ui

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.aspectRatio
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.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowRight
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.aegir.demo.MapActivity
import com.aegir.demo.R
import kotlinx.coroutines.launch

private val IOS_SYSTEM_BLUE = Color(0xFF007AFF)
private val IOS_GROUPED_BG = Color(0xFFF2F2F7)
private val IOS_CELL_BG = Color.White
private val IOS_SECONDARY_LABEL = Color(0xFF6D6D72)
private val IOS_PLACEHOLDER = Color(0xFFC4C4C6)
private val IOS_PRIMARY_TEXT = Color(0xFF1C1C1E)
private val IOS_SEPARATOR = Color(0xFFC6C6C8)

class VenueListActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val venues = discoverBuiltInVenues(this)
        setContent {
            MaterialTheme {
                VenueListScreen(
                    venues = venues,
                    onPickBuiltIn = { id -> launchMap(id, baseUrl = null) },
                    onPickCustom = { id, url -> launchMap(id, baseUrl = url) },
                )
            }
        }
    }

    private fun launchMap(venueId: String, baseUrl: String?) {
        val intent = Intent(this, MapActivity::class.java).apply {
            putExtra("embedded", true)
            putExtra("venue_id", venueId)
            if (!baseUrl.isNullOrBlank()) {
                putExtra("base_url", baseUrl)
            }
        }
        startActivity(intent)
    }

    companion object {
        private const val STATIC_VENUE = "AEGIRH"
        private const val ASSET_PREFIX = "venue_map_"

        fun discoverBuiltInVenues(context: Context): List<String> {
            // Venues ship either as loose asset folders or as venue_map_<ID>.zip
            // (zipped to stay under the APK 65,535-entry limit).
            val ids = context.assets.list("")
                .orEmpty()
                .filter { it.startsWith(ASSET_PREFIX) }
                .map { it.removePrefix(ASSET_PREFIX).removeSuffix(".zip") }
                .filter { it.isNotBlank() }
                .toMutableSet()
            ids.add(STATIC_VENUE)
            return ids.sorted()
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun VenueListScreen(
    venues: List<String>,
    onPickBuiltIn: (String) -> Unit,
    onPickCustom: (venueId: String, baseUrl: String) -> Unit,
) {
    val context = LocalContext.current
    val prefs = remember { AppPrefs(context) }

    var baseUrl by remember { mutableStateOf(prefs.lastBaseURL.orEmpty()) }
    var venueId by remember { mutableStateOf(prefs.lastVenueID.orEmpty()) }
    var showPicker by remember { mutableStateOf(false) }
    var customError by remember { mutableStateOf<String?>(null) }

    Scaffold(
        containerColor = IOS_GROUPED_BG,
        topBar = {
            CenterAlignedTopAppBar(
                title = {
                    Text(
                        text = "VM-SDK Test",
                        fontSize = 17.sp,
                        fontWeight = FontWeight.SemiBold,
                        color = IOS_PRIMARY_TEXT,
                    )
                },
                colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
                    containerColor = IOS_GROUPED_BG,
                ),
            )
        },
    ) { padding ->
        Column(
            modifier = Modifier
                .padding(padding)
                .fillMaxSize()
                .background(IOS_GROUPED_BG),
        ) {
            SectionHeader("Built-in Venues")
            GroupedCard {
                BuiltInRow(onClick = { showPicker = true })
            }

            Spacer(modifier = Modifier.height(28.dp))
            SectionHeader("Custom Venue (HTTPS)")
            GroupedCard {
                FieldRow(
                    label = "Base URL",
                    value = baseUrl,
                    onValueChange = { baseUrl = it },
                    placeholder = "https://example.com/vmd",
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
                )
                CellDivider()
                FieldRow(
                    label = "Venue ID",
                    value = venueId,
                    onValueChange = { venueId = it },
                    placeholder = "VENUE_ID",
                    keyboardOptions = KeyboardOptions(
                        keyboardType = KeyboardType.Text,
                        capitalization = KeyboardCapitalization.Characters,
                    ),
                )
                CellDivider()
                ButtonRow(
                    text = "Load Custom Venue",
                    onClick = {
                        val trimmedUrl = baseUrl.trim()
                        val trimmedId = venueId.trim()
                        if (trimmedUrl.isEmpty() || trimmedId.isEmpty()) {
                            customError = "Provide both a Base URL and Venue ID."
                            return@ButtonRow
                        }
                        customError = null
                        prefs.lastBaseURL = trimmedUrl
                        prefs.lastVenueID = trimmedId
                        onPickCustom(trimmedId, trimmedUrl)
                    },
                )
            }

            customError?.let { err ->
                Text(
                    text = err,
                    color = MaterialTheme.colorScheme.error,
                    fontSize = 13.sp,
                    modifier = Modifier.padding(start = 32.dp, end = 32.dp, top = 6.dp),
                )
            }

            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
                    .padding(vertical = 24.dp),
                contentAlignment = Alignment.Center,
            ) {
                Image(
                    painter = painterResource(id = R.drawable.aegir_logo),
                    contentDescription = "Aegir",
                    // Force the layout to honor the source aspect ratio (~2.64).
                    // Without this the `drawable-nodpi` qualifier exposes the
                    // painter's intrinsic px-as-dp height (~36dp on xxhdpi) and
                    // ContentScale.Fit shrinks the bitmap to fit that box.
                    modifier = Modifier
                        .width(200.dp)
                        .aspectRatio(288f / 109f),
                )
            }
        }

        if (showPicker) {
            VenuePickerSheet(
                venues = venues,
                onSelect = { id ->
                    showPicker = false
                    onPickBuiltIn(id)
                },
                onDismiss = { showPicker = false },
            )
        }
    }
}

@Composable
private fun SectionHeader(text: String) {
    Text(
        text = text.uppercase(),
        color = IOS_SECONDARY_LABEL,
        fontSize = 13.sp,
        fontWeight = FontWeight.Normal,
        modifier = Modifier.padding(start = 32.dp, end = 32.dp, top = 18.dp, bottom = 6.dp),
    )
}

@Composable
private fun GroupedCard(content: @Composable () -> Unit) {
    Surface(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp),
        shape = RoundedCornerShape(10.dp),
        color = IOS_CELL_BG,
    ) {
        Column(modifier = Modifier.fillMaxWidth()) { content() }
    }
}

@Composable
private fun CellDivider() {
    Divider(
        color = IOS_SEPARATOR,
        thickness = 0.5.dp,
        modifier = Modifier.padding(start = 16.dp),
    )
}

@Composable
private fun BuiltInRow(onClick: () -> Unit) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .heightIn(min = 44.dp)
            .clickable(onClick = onClick)
            .padding(horizontal = 16.dp, vertical = 12.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Text(
            text = "Select Venue...",
            color = IOS_SYSTEM_BLUE,
            fontSize = 17.sp,
            modifier = Modifier.weight(1f),
        )
        Icon(
            imageVector = Icons.Default.KeyboardArrowRight,
            contentDescription = null,
            tint = IOS_SECONDARY_LABEL.copy(alpha = 0.6f),
        )
    }
}

@Composable
private fun FieldRow(
    label: String,
    value: String,
    onValueChange: (String) -> Unit,
    placeholder: String,
    keyboardOptions: KeyboardOptions,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .heightIn(min = 44.dp)
            .padding(horizontal = 16.dp, vertical = 8.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Text(
            text = label,
            color = IOS_SECONDARY_LABEL,
            fontSize = 13.sp,
            fontWeight = FontWeight.Medium,
            modifier = Modifier.width(70.dp),
        )
        Spacer(modifier = Modifier.width(12.dp))
        Box(modifier = Modifier.weight(1f)) {
            BasicTextField(
                value = value,
                onValueChange = onValueChange,
                singleLine = true,
                textStyle = TextStyle(
                    color = IOS_PRIMARY_TEXT,
                    fontSize = 15.sp,
                ),
                keyboardOptions = keyboardOptions,
                cursorBrush = SolidColor(IOS_SYSTEM_BLUE),
                modifier = Modifier.fillMaxWidth(),
            )
            if (value.isEmpty()) {
                Text(
                    text = placeholder,
                    color = IOS_PLACEHOLDER,
                    fontSize = 15.sp,
                )
            }
        }
    }
}

@Composable
private fun ButtonRow(text: String, onClick: () -> Unit) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .heightIn(min = 44.dp)
            .clickable(onClick = onClick)
            .padding(vertical = 12.dp),
        contentAlignment = Alignment.Center,
    ) {
        Text(
            text = text,
            color = IOS_SYSTEM_BLUE,
            fontSize = 17.sp,
            textAlign = TextAlign.Center,
        )
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun VenuePickerSheet(
    venues: List<String>,
    onSelect: (String) -> Unit,
    onDismiss: () -> Unit,
) {
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = false)
    val scope = rememberCoroutineScope()

    ModalBottomSheet(
        onDismissRequest = onDismiss,
        sheetState = sheetState,
        containerColor = IOS_GROUPED_BG,
    ) {
        Text(
            text = "Built-in Venues",
            color = IOS_PRIMARY_TEXT,
            fontSize = 17.sp,
            fontWeight = FontWeight.SemiBold,
            modifier = Modifier.padding(start = 24.dp, top = 8.dp, bottom = 12.dp),
        )
        CompositionLocalProvider(LocalContentColor provides IOS_PRIMARY_TEXT) {
            Surface(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 0.dp),
                shape = RoundedCornerShape(10.dp),
                color = IOS_CELL_BG,
            ) {
                LazyColumn(
                    modifier = Modifier.fillMaxWidth(),
                    verticalArrangement = Arrangement.spacedBy(0.dp),
                ) {
                    items(venues, key = { it }) { id ->
                        VenueRow(
                            id = id,
                            onClick = {
                                scope.launch {
                                    sheetState.hide()
                                    onSelect(id)
                                }
                            },
                        )
                        if (id != venues.last()) {
                            CellDivider()
                        }
                    }
                }
            }
        }
        Spacer(modifier = Modifier.height(16.dp))
    }

    LaunchedEffect(Unit) {
        sheetState.show()
    }
}

@Composable
private fun VenueRow(id: String, onClick: () -> Unit) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .heightIn(min = 44.dp)
            .clickable(onClick = onClick)
            .padding(horizontal = 16.dp, vertical = 12.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Text(
            text = id,
            color = IOS_PRIMARY_TEXT,
            fontSize = 17.sp,
            modifier = Modifier.weight(1f),
        )
    }
}
