package il.co.organicai.agent

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * Minimal shell: if we already hold a session, start the agent service. Otherwise
 * show the 2FA login (email + password -> emailed code), matching ADR-47.
 *
 * The heavy lifting (the controllable browser) lives in AgentWebView, driven by
 * AgentService — this screen is just onboarding.
 */
class MainActivity : AppCompatActivity() {

    private val scope = CoroutineScope(Dispatchers.Main)
    private val worker = WorkerClient()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            requestPermissions(arrayOf(android.Manifest.permission.POST_NOTIFICATIONS), 1)
        }
        if (SessionStore.token(this) != null) { startAgent(); finish(); return }
        setContentView(loginView())
    }

    // Two-step 2FA form built in code to keep the scaffold dependency-free.
    private lateinit var idField: EditText
    private lateinit var secretField: EditText
    private lateinit var actionBtn: Button
    private lateinit var hint: TextView
    private var pendingId: String? = null

    private fun loginView() = LinearLayout(this).apply {
        orientation = LinearLayout.VERTICAL
        setPadding(48, 96, 48, 48)
        addView(TextView(this@MainActivity).apply { text = "OrganicAI"; textSize = 24f })
        idField = EditText(this@MainActivity).apply { hint = "אימייל או שם משתמש" }
        secretField = EditText(this@MainActivity).apply { hint = "סיסמה"; inputType = 0x81 /* textPassword */ }
        hint = TextView(this@MainActivity)
        actionBtn = Button(this@MainActivity).apply { text = "היכנס"; setOnClickListener { onAction() } }
        addView(idField); addView(secretField); addView(hint); addView(actionBtn)
    }

    private fun onAction() {
        val id = idField.text.toString().trim()
        val secret = secretField.text.toString().trim()
        actionBtn.isEnabled = false
        scope.launch {
            if (pendingId == null) {
                // Factor 1: password -> code emailed.
                val otp = withContext(Dispatchers.IO) { worker.loginPassword(id, secret) }
                actionBtn.isEnabled = true
                if (otp) {
                    pendingId = id
                    hint.text = "שלחנו קוד לאימייל — הזן אותו כאן"
                    secretField.setText(""); secretField.hint = "קוד בן 6 ספרות"; secretField.inputType = 0x02
                    actionBtn.text = "אמת קוד"
                } else toast("אימייל או סיסמה שגויים")
            } else {
                // Factor 2: the emailed code -> session.
                val ok = withContext(Dispatchers.IO) { worker.verifyOtp(pendingId!!, secret) }
                actionBtn.isEnabled = true
                if (ok) {
                    SessionStore.save(this@MainActivity, worker.token!!, pendingId!!)
                    startAgent(); finish()
                } else toast("קוד שגוי")
            }
        }
    }

    private fun startAgent() {
        val i = Intent(this, AgentService::class.java)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) startForegroundService(i) else startService(i)
    }

    private fun toast(s: String) = Toast.makeText(this, s, Toast.LENGTH_SHORT).show()
}
