package com.comtropy.cargoradar

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.text.InputType
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import kotlin.math.roundToInt

class MainActivity : Activity() {
    private lateinit var preferences: SharedPreferences
    private lateinit var serverUrlInput: EditText
    private lateinit var driverIdInput: EditText
    private lateinit var vehicleNoInput: EditText
    private lateinit var tokenInput: EditText
    private lateinit var statusText: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        preferences = getSharedPreferences("cargo_radar_config", MODE_PRIVATE)
        setContentView(buildContentView())
    }

    private fun buildContentView(): View {
        val container = LinearLayout(this).apply {
            orientation = LinearLayout.VERTICAL
            setPadding(dp(20), dp(18), dp(20), dp(18))
        }

        val title = TextView(this).apply {
            text = getString(R.string.app_name)
            textSize = 24f
            setTextColor(0xff17212b.toInt())
            setTypeface(typeface, android.graphics.Typeface.BOLD)
        }
        container.addView(title, matchWrap())

        val subtitle = TextView(this).apply {
            text = "운행 위치 업로드"
            textSize = 14f
            setTextColor(0xff657487.toInt())
        }
        container.addView(subtitle, marginBottom(20))

        serverUrlInput = input(
            key = "server_url",
            defaultValue = "http://10.0.2.2:8080",
            hint = "서버 URL"
        )
        driverIdInput = input("driver_id", "demo-driver", "기사 ID")
        vehicleNoInput = input("vehicle_no", "SEOUL-12-3456", "차량 번호")
        tokenInput = input("device_token", "demo-token", "기기 토큰")

        addField(container, "서버 URL", serverUrlInput)
        addField(container, "기사 ID", driverIdInput)
        addField(container, "차량 번호", vehicleNoInput)
        addField(container, "기기 토큰", tokenInput)

        val permissionButton = Button(this).apply {
            text = "권한 확인"
            setOnClickListener { requestRuntimePermissions() }
        }
        container.addView(permissionButton, marginTop(8))

        val startButton = Button(this).apply {
            text = "운행 시작"
            setOnClickListener { startTracking() }
        }
        container.addView(startButton, marginTop(8))

        val stopButton = Button(this).apply {
            text = "운행 종료"
            setOnClickListener { stopTracking() }
        }
        container.addView(stopButton, marginTop(8))

        val settingsButton = Button(this).apply {
            text = "앱 위치 설정"
            setOnClickListener {
                startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                    data = android.net.Uri.parse("package:$packageName")
                })
            }
        }
        container.addView(settingsButton, marginTop(8))

        statusText = TextView(this).apply {
            text = "대기 중"
            textSize = 14f
            setTextColor(0xff17212b.toInt())
        }
        container.addView(statusText, marginTop(18))

        return ScrollView(this).apply {
            addView(container)
        }
    }

    private fun addField(container: LinearLayout, labelText: String, input: EditText) {
        val label = TextView(this).apply {
            text = labelText
            textSize = 13f
            setTextColor(0xff657487.toInt())
            setTypeface(typeface, android.graphics.Typeface.BOLD)
        }
        container.addView(label, marginTop(14))
        container.addView(input, matchWrap())
    }

    private fun input(key: String, defaultValue: String, hint: String): EditText {
        return EditText(this).apply {
            setText(preferences.getString(key, defaultValue))
            this.hint = hint
            inputType = InputType.TYPE_CLASS_TEXT
            setSingleLine(true)
        }
    }

    private fun requestRuntimePermissions() {
        val permissions = mutableListOf(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        )

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions.add(Manifest.permission.POST_NOTIFICATIONS)
        }

        requestPermissions(permissions.toTypedArray(), REQUEST_PERMISSIONS)
    }

    private fun startTracking() {
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestRuntimePermissions()
            statusText.text = "위치 권한이 필요합니다."
            return
        }

        saveConfig()

        val intent = Intent(this, LocationUploadService::class.java).apply {
            action = LocationUploadService.ACTION_START
            putExtra(LocationUploadService.EXTRA_SERVER_URL, serverUrlInput.text.toString().trim())
            putExtra(LocationUploadService.EXTRA_DRIVER_ID, driverIdInput.text.toString().trim())
            putExtra(LocationUploadService.EXTRA_VEHICLE_NO, vehicleNoInput.text.toString().trim())
            putExtra(LocationUploadService.EXTRA_DEVICE_TOKEN, tokenInput.text.toString().trim())
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent)
        } else {
            startService(intent)
        }

        statusText.text = "위치 업로드를 시작했습니다."
    }

    private fun stopTracking() {
        val intent = Intent(this, LocationUploadService::class.java).apply {
            action = LocationUploadService.ACTION_STOP
        }
        startService(intent)
        statusText.text = "위치 업로드를 종료했습니다."
    }

    private fun saveConfig() {
        preferences.edit()
            .putString("server_url", serverUrlInput.text.toString().trim())
            .putString("driver_id", driverIdInput.text.toString().trim())
            .putString("vehicle_no", vehicleNoInput.text.toString().trim())
            .putString("device_token", tokenInput.text.toString().trim())
            .apply()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_PERMISSIONS && grantResults.any { it == PackageManager.PERMISSION_GRANTED }) {
            statusText.text = "권한 확인 완료"
        }
    }

    private fun matchWrap(): LinearLayout.LayoutParams {
        return LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
    }

    private fun marginTop(topDp: Int): LinearLayout.LayoutParams {
        return matchWrap().apply {
            topMargin = dp(topDp)
        }
    }

    private fun marginBottom(bottomDp: Int): LinearLayout.LayoutParams {
        return matchWrap().apply {
            bottomMargin = dp(bottomDp)
        }
    }

    private fun dp(value: Int): Int {
        return (value * resources.displayMetrics.density).roundToInt()
    }

    companion object {
        private const val REQUEST_PERMISSIONS = 1001
    }
}
