package com.hipograf.companion.ui

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.hipograf.companion.HipografApp
import com.hipograf.companion.api.HipografApi
import com.hipograf.companion.databinding.ActivityLoginBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class LoginActivity : AppCompatActivity() {

    private lateinit var binding: ActivityLoginBinding

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

        // If already logged in, go straight to dashboard
        val prefs = getSharedPreferences("hipograf", MODE_PRIVATE)
        if (prefs.getString("token", null) != null) {
            startActivity(Intent(this, DashboardActivity::class.java))
            finish()
            return
        }

        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.btnLogin.setOnClickListener { attemptLogin() }
    }

    private fun attemptLogin() {
        val identifier = binding.etIdentifier.text.toString().trim()
        val password = binding.etPassword.text.toString()

        if (identifier.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "Please fill in all fields", Toast.LENGTH_SHORT).show()
            return
        }

        binding.btnLogin.isEnabled = false
        binding.btnLogin.text = "Logging in..."

        lifecycleScope.launch {
            val result = withContext(Dispatchers.IO) {
                HipografApi.login(identifier, password)
            }

            result.fold(
                onSuccess = { loginResp ->
                    // Save token and user info
                    val prefs = getSharedPreferences("hipograf", MODE_PRIVATE)
                    prefs.edit()
                        .putString("token", loginResp.accessToken)
                        .putInt("token_expires_in", loginResp.expiresIn)
                        .putLong("token_saved_at", System.currentTimeMillis())
                        .apply()

                    // Schedule background sync
                    (application as HipografApp).scheduleSyncWorker()

                    Toast.makeText(this@LoginActivity, "Logged in!", Toast.LENGTH_SHORT).show()
                    startActivity(Intent(this@LoginActivity, DashboardActivity::class.java))
                    finish()
                },
                onFailure = { error ->
                    Toast.makeText(this@LoginActivity, error.message, Toast.LENGTH_LONG).show()
                    binding.btnLogin.isEnabled = true
                    binding.btnLogin.text = "Log In"
                }
            )
        }
    }
}
