package com.example.aprs

import android.Manifest
import android.content.Context
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
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.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat

var permissionGranted by mutableStateOf(false)

class MainActivity : ComponentActivity() {

    internal val permissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
        permissionGranted = granted
    }

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

        // Включаем полноэкранный режим
        WindowCompat.setDecorFitsSystemWindows(window, false)
        WindowInsetsControllerCompat(window, window.decorView).apply {
            hide(WindowInsetsCompat.Type.statusBars())
            hide(WindowInsetsCompat.Type.navigationBars())
            systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        }

        // Делаем контент за статус-баром и навигацией
        window.setFlags(
            WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
            WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
        )

        setContent {
            MaterialTheme(
                colorScheme = darkColorScheme()
            ) {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = Color(0xFF0D0D0D)
                ) {
                    CoordinateConverterScreen(this)
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CoordinateConverterScreen(activity: MainActivity) {
    var location by remember { mutableStateOf<Location?>(null) }
    var isUpdating by remember { mutableStateOf(false) }
    val context = activity.applicationContext
    val scrollState = rememberScrollState()

    LaunchedEffect(Unit) {
        val granted = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == android.content.pm.PackageManager.PERMISSION_GRANTED
        permissionGranted = granted
        if (!granted) {
            activity.permissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
        }
    }

    DisposableEffect(permissionGranted) {
        val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        val listener = object : LocationListener {
            override fun onLocationChanged(loc: Location) {
                location = loc
                isUpdating = false
            }

            override fun onProviderEnabled(provider: String) {}
            override fun onProviderDisabled(provider: String) {}
            override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}
        }

        if (permissionGranted) {
            try {
                isUpdating = true
                val last = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER) ?: lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
                if (last != null) {
                    location = last
                    isUpdating = false
                }
                lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 0f, listener)
            } catch (e: SecurityException) {
                isUpdating = false
            }
        }

        onDispose {
            lm.removeUpdates(listener)
        }
    }

    val lat = location?.latitude ?: 0.0
    val lon = location?.longitude ?: 0.0
    val hasLocation = location != null

    val aprs = if (hasLocation) LocationUtils.toAprs(lat, lon) else "—"
    val maiden = if (hasLocation) LocationUtils.toMaidenhead(lat, lon) else "—"
    val dmsLat = if (hasLocation) toDMS(lat, true) else "—"
    val dmsLon = if (hasLocation) toDMS(lon, false) else "—"

    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(scrollState)
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // Header
        Spacer(modifier = Modifier.height(24.dp))
        Text(
            text = "Конвертор координат",
            fontSize = 28.sp,
            fontWeight = FontWeight.Bold,
            color = Color.White
        )
        Text(
            text = "GPS → APRS, Maidenhead",
            fontSize = 14.sp,
            color = Color.Gray,
            modifier = Modifier.padding(top = 4.dp)
        )

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

        // Status indicator
        Row(
            modifier = Modifier
                .clip(RoundedCornerShape(16.dp))
                .background(
                    if (isUpdating) Brush.horizontalGradient(listOf(Color(0xFFFFA500), Color(0xFFFF6600)))
                    else if (hasLocation) Brush.horizontalGradient(listOf(Color(0xFF00C853), Color(0xFF69F0AE)))
                    else Brush.horizontalGradient(listOf(Color(0xFFB0BEC5), Color(0xFF78909C)))
                )
                .padding(horizontal = 16.dp, vertical = 8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = if (isUpdating) Icons.Default.Refresh else if (hasLocation) Icons.Default.CheckCircle else Icons.Default.LocationOff,
                contentDescription = null,
                tint = Color.White,
                modifier = Modifier.size(20.dp)
            )
            Spacer(modifier = Modifier.width(8.dp))
            Text(
                text = if (isUpdating) "Получение GPS..." else if (hasLocation) "GPS активен" else "Нет GPS",
                color = Color.White,
                fontWeight = FontWeight.Medium
            )
        }

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

        // Decimal coordinates card
        CoordinateCard(
            title = "Десятичные координаты",
            icon = Icons.Default.MyLocation,
            gradient = listOf(Color(0xFF2196F3), Color(0xFF64B5F6))
        ) {
            CoordinateRow(label = "Широта", value = if (hasLocation) String.format("%.6f°", lat) else "—")
            Spacer(modifier = Modifier.height(8.dp))
            CoordinateRow(label = "Долгота", value = if (hasLocation) String.format("%.6f°", lon) else "—")
        }

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

        // DMS coordinates card
        CoordinateCard(
            title = "Градусы, минуты, секунды",
            icon = Icons.Default.Place,
            gradient = listOf(Color(0xFF9C27B0), Color(0xFFBA68C8))
        ) {
            CoordinateRow(label = "Широта", value = dmsLat)
            Spacer(modifier = Modifier.height(8.dp))
            CoordinateRow(label = "Долгота", value = dmsLon)
        }

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

        // APRS card
        CoordinateCard(
            title = "APRS формат",
            icon = Icons.Default.Radio,
            gradient = listOf(Color(0xFFFF5722), Color(0xFFFF8A65))
        ) {
            Text(
                text = aprs,
                fontSize = 16.sp,
                fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
                color = Color(0xFFFFCCBC),
                modifier = Modifier.padding(vertical = 8.dp)
            )
        }

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

        // Maidenhead card
        CoordinateCard(
            title = "Maidenhead (QTH локатор)",
            icon = Icons.Default.GridOn,
            gradient = listOf(Color(0xFF00BCD4), Color(0xFF4DD0E1))
        ) {
            Text(
                text = maiden,
                fontSize = 24.sp,
                fontWeight = FontWeight.Bold,
                fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
                color = Color(0xFFB2EBF2),
                modifier = Modifier.padding(vertical = 8.dp)
            )
        }

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

        // Footer
        Text(
            text = "© 2026 UA1ZBE",
            fontSize = 14.sp,
            fontWeight = FontWeight.Medium,
            color = Color(0xFF9C27B0)
        )

        Spacer(modifier = Modifier.height(16.dp))
    }
}

@Composable
fun CoordinateCard(
    title: String,
    icon: ImageVector,
    gradient: List<Color>,
    content: @Composable ColumnScope.() -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(16.dp),
        colors = CardDefaults.cardColors(containerColor = Color(0xFF1A1A1A))
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Box(
                    modifier = Modifier
                        .size(40.dp)
                        .clip(RoundedCornerShape(12.dp))
                        .background(Brush.horizontalGradient(gradient)),
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        imageVector = icon,
                        contentDescription = null,
                        tint = Color.White,
                        modifier = Modifier.size(22.dp)
                    )
                }
                Spacer(modifier = Modifier.width(12.dp))
                Text(
                    text = title,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.SemiBold,
                    color = Color.White
                )
            }
            Spacer(modifier = Modifier.height(16.dp))
            content()
        }
    }
}

@Composable
fun CoordinateRow(label: String, value: String) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = label,
            fontSize = 14.sp,
            color = Color.Gray
        )
        Text(
            text = value,
            fontSize = 16.sp,
            fontWeight = FontWeight.Medium,
            color = Color.White,
            fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace
        )
    }
}

fun toDMS(coordinate: Double, isLatitude: Boolean): String {
    val abs = kotlin.math.abs(coordinate)
    val deg = abs.toInt()
    val minFloat = (abs - deg) * 60
    val min = minFloat.toInt()
    val sec = (minFloat - min) * 60
    val direction = when {
        isLatitude -> if (coordinate >= 0) "N" else "S"
        else -> if (coordinate >= 0) "E" else "W"
    }
    return String.format("%d° %d' %.2f\" %s", deg, min, sec, direction)
}
