package id.ac.ubharajaya.sistemakademik

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import com.google.android.gms.location.LocationServices
import id.ac.ubharajaya.sistemakademik.ui.theme.SistemAkademikTheme
import java.text.SimpleDateFormat
import java.util.*
import kotlin.concurrent.thread
import java.net.HttpURLConnection
import java.net.URL
import org.json.JSONObject

// ================== UTILS ==================
fun kirimKeN8n(context: ComponentActivity, absensi: Absensi) {
    thread {
        try {
            val url = URL("https://n8n.lab.ubharajaya.ac.id/webhook/23c6993d-1792-48fb-ad1c-ffc78a3e6254")
            val conn = url.openConnection() as HttpURLConnection
            conn.requestMethod = "POST"
            conn.setRequestProperty("Content-Type", "application/json")
            conn.doOutput = true
            val json = absensi.toJson()
            conn.outputStream.use { it.write(json.toString().toByteArray()) }
            val responseCode = conn.responseCode
            context.runOnUiThread {
                Toast.makeText(
                    context,
                    if (responseCode == 200) "Absensi diterima server" else "Absensi ditolak server",
                    Toast.LENGTH_SHORT
                ).show()
            }
            conn.disconnect()
        } catch (_: Exception) {
            context.runOnUiThread {
                Toast.makeText(context, "Gagal kirim ke server", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

// ================== MAIN ACTIVITY ==================
class MainActivity : ComponentActivity() {

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

        setContent {
            SistemAkademikTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    AbsensiScreen(modifier = Modifier.padding(innerPadding), activity = this)
                }
            }
        }
    }
}

// ================== COMPOSABLE UI ==================
@Composable
fun AbsensiScreen(modifier: Modifier = Modifier, activity: ComponentActivity) {
    val context = LocalContext.current
    val session = remember { SessionManager(context) }

    var lokasi by remember { mutableStateOf("Koordinat: -") }
    var latitude by remember { mutableStateOf<Double?>(null) }
    var longitude by remember { mutableStateOf<Double?>(null) }
    var foto by remember { mutableStateOf<Bitmap?>(null) }
    var waktuAbsensi by remember { mutableStateOf<String?>(null) }
    val absensiList = remember { mutableStateListOf<Absensi>() }

    val fusedLocationClient = LocationServices.getFusedLocationProviderClient(context)

    // ================== STATE WARNA ==================
    var primaryColor by remember { mutableStateOf(Color(0xFF6200EE)) }
    var backgroundColor by remember { mutableStateOf(Color(0xFFF2F2F2)) }

    val colors = listOf(
        Color.Red, Color.Green, Color.Blue, Color.Magenta, Color.Cyan,
        Color.Yellow, Color.Gray, Color.DarkGray, Color.Black, Color(0xFFFF9800),
        Color(0xFF9C27B0), Color(0xFF4CAF50), Color(0xFF03A9F4), Color(0xFFE91E63)
    )

    // ===== Permission & Kamera =====
    val locationPermissionLauncher =
        rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
            if (granted) {
                if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED
                ) {
                    fusedLocationClient.lastLocation
                        .addOnSuccessListener { location ->
                            if (location != null) {
                                latitude = location.latitude
                                longitude = location.longitude
                                lokasi = "Lat: ${location.latitude}\nLon: ${location.longitude}"
                            } else {
                                lokasi = "Lokasi tidak tersedia"
                            }
                        }
                        .addOnFailureListener { lokasi = "Gagal mengambil lokasi" }
                }
            } else {
                Toast.makeText(context, "Izin lokasi ditolak", Toast.LENGTH_SHORT).show()
            }
        }

    val cameraLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val bitmap: Bitmap? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                result.data?.extras?.getParcelable("data", Bitmap::class.java)
            } else {
                @Suppress("DEPRECATION")
                result.data?.extras?.getParcelable("data")
            }

            if (bitmap != null) {
                foto = bitmap
                Toast.makeText(context, "Foto berhasil diambil", Toast.LENGTH_SHORT).show()
            }
        }
    }

    val cameraPermissionLauncher =
        rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
            if (granted) {
                val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                cameraLauncher.launch(intent)
            } else {
                Toast.makeText(context, "Izin kamera ditolak", Toast.LENGTH_SHORT).show()
            }
        }

    LaunchedEffect(Unit) {
        locationPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
    }

    // ================== UI ==================
    Column(
        modifier = modifier
            .fillMaxSize()
            .background(backgroundColor)
            .padding(24.dp)
    ) {
        Text(
            text = "Absensi Akademik",
            style = MaterialTheme.typography.titleLarge,
            color = primaryColor
        )
        Spacer(modifier = Modifier.height(16.dp))

        // PALETTE WARNA BULETAN
        Text("Pilih Warna Tema:", style = MaterialTheme.typography.bodyMedium, color = primaryColor)
        Spacer(modifier = Modifier.height(8.dp))
        Row(modifier = Modifier.horizontalScroll(rememberScrollState())) {
            colors.forEach { color ->
                Box(
                    modifier = Modifier
                        .size(40.dp)
                        .padding(4.dp)
                        .background(color, shape = CircleShape)
                        .clickable {
                            primaryColor = color
                            backgroundColor = color.copy(alpha = 0.1f)
                        }
                )
            }
        }

        Spacer(modifier = Modifier.height(16.dp))
        Text(text = lokasi, color = primaryColor)
        Spacer(modifier = Modifier.height(16.dp))

        Button(
            onClick = { cameraPermissionLauncher.launch(Manifest.permission.CAMERA) },
            modifier = Modifier.fillMaxWidth(),
            colors = ButtonDefaults.buttonColors(containerColor = primaryColor)
        ) { Text("Ambil Foto") }

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

        Button(
            onClick = {
                if (latitude != null && longitude != null && foto != null) {
                    val waktu = SimpleDateFormat("dd MMM yyyy HH:mm:ss", Locale.getDefault()).format(System.currentTimeMillis())
                    waktuAbsensi = waktu

                    val absensi = Absensi(
                        npm = session.getUserNpm() ?: "Faris Naufal Priatna",
                        nama = session.getUserName() ?: "202310715123",
                        latitude = latitude!!,
                        longitude = longitude!!,
                        waktu = waktu,
                        foto = foto!!
                    )
                    kirimKeN8n(activity, absensi)
                    absensiList.add(absensi)
                } else {
                    Toast.makeText(context, "⚠️ Absensi ditolak: Silahkan Foto Dlu Kocak", Toast.LENGTH_SHORT).show()
                }
            },
            modifier = Modifier.fillMaxWidth(),
            colors = ButtonDefaults.buttonColors(containerColor = primaryColor)
        ) { Text("Kirim Absensi") }

        Spacer(modifier = Modifier.height(16.dp))
        waktuAbsensi?.let { Text("Waktu Absensi: $it", color = primaryColor) }

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

        // ================== LOGOUT BUTTON ==================
        Button(
            onClick = {
                session.logout()
                context.startActivity(Intent(context, LoginActivity::class.java))
                (context as ComponentActivity).finish()
            },
            modifier = Modifier.fillMaxWidth(),
            colors = ButtonDefaults.buttonColors(containerColor = Color.Red)
        ) {
            Text("Logout")
        }

        Spacer(modifier = Modifier.height(16.dp))
        Text("Riwayat Kehadiran", color = primaryColor)
        Spacer(modifier = Modifier.height(12.dp))

        if (absensiList.isEmpty()) Text("Belum ada absensi", color = primaryColor)
        else LazyColumn {
            items(absensiList) { item ->
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 4.dp),
                    elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
                ) {
                    Column(modifier = Modifier.padding(12.dp)) {
                        Text("Nama: ${item.nama}", color = primaryColor)
                        Text("NPM: ${item.npm}", color = primaryColor)
                        Text("Waktu: ${item.waktu}", color = primaryColor)
                        Text("Lat: ${item.latitude}, Lon: ${item.longitude}", color = primaryColor)
                        Spacer(modifier = Modifier.height(8.dp))
                        Image(
                            bitmap = item.foto.asImageBitmap(),
                            contentDescription = "Foto Absensi",
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(150.dp)
                        )
                    }
                }
            }
        }
    }
}
