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.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
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.net.HttpURLConnection
import java.net.URL
import java.text.SimpleDateFormat
import java.util.*
import kotlin.concurrent.thread
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign



/* ================== UTILS ================== */

/**
 * Kirim data Absensi ke server N8N
 */
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

    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)

    /* ===== Permission Lokasi ===== */
    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()
            }
        }

    /* ===== Kamera ===== */
    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()
            }
        }

    /* ===== Request Awal ===== */
    LaunchedEffect(Unit) {
        locationPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
    }

    /* ===== UI ===== */
    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(24.dp)
    ) {
        Text(
            text = "ABSENSI AKADEMIK",
            style = MaterialTheme.typography.titleLarge.copy(
                fontWeight = FontWeight.Bold
            ),
            modifier = Modifier.fillMaxWidth(),
            textAlign = TextAlign.Center
        )


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

        Button(
            onClick = { cameraPermissionLauncher.launch(Manifest.permission.CAMERA) },
            modifier = Modifier.fillMaxWidth()

        ) {
            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 = "202310715220",
                        nama = "Muhammad Fadzel Hadean Rukrus",
                        latitude = latitude!!,
                        longitude = longitude!!,
                        waktu = waktu,
                        foto = foto!!
                    )

                    // Kirim ke server
                    kirimKeN8n(activity, absensi)

                    // Simpan ke riwayat lokal
                    absensiList.add(absensi)
                } else {
                    Toast.makeText(context, "❗ABSEN DITOLAK, FOTO DULU❗", Toast.LENGTH_SHORT)
                        .show()
                }
            },
            modifier = Modifier.fillMaxWidth()
        ) {
            Text("KIRIM ABSENSI")
        }

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

        waktuAbsensi?.let {
            Text(
                text = "Waktu Absensi: $it",
                style = MaterialTheme.typography.bodyLarge,
                modifier = Modifier.fillMaxWidth(),
                textAlign = TextAlign.Center
            )
        }

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

        Text(
            text = "RIWAYAT KEHADIRAN",
            style = MaterialTheme.typography.titleMedium.copy(
                fontWeight = FontWeight.Bold
            ),
            modifier = Modifier.fillMaxWidth(),
            textAlign = TextAlign.Center
        )

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

        if (absensiList.isEmpty()) {
            Text(
                text = "BELUM ADA ABSENSI",
                style = MaterialTheme.typography.bodyMedium,
                modifier = Modifier.fillMaxWidth(),
                textAlign = TextAlign.Center
            )

        } else {
            LazyColumn(modifier = Modifier.fillMaxWidth()) {
                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}")
                            Text("NPM: ${item.npm}")
                            Text("Waktu: ${item.waktu}")
                            Text("Lat: ${item.latitude}, Lon: ${item.longitude}")
                            Spacer(modifier = Modifier.height(8.dp))
                            Image(
                                bitmap = item.foto.asImageBitmap(),
                                contentDescription = "Foto Absensi",
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(150.dp)
                            )
                        }
                    }
                }
            }
            Spacer(modifier = Modifier.height(16.dp))

            Button(
                onClick = {
                    // Pindah ke LoginActivity
                    val intent = Intent(activity, LoginActivity::class.java)
                    activity.startActivity(intent)
                    activity.finish() // Hapus MainActivity dari stack
                },
                modifier = Modifier.fillMaxWidth(),
                colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error)
            ) {
                Text("LOGOUT", color = MaterialTheme.colorScheme.onError)
            }
        }
    }
}