package com.gestoreasy.ui.client

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.gestoreasy.MobileApp
import com.gestoreasy.R
import com.gestoreasy.database.entities.Client
import com.gestoreasy.databinding.ActivityClientFormBinding
import com.gestoreasy.repository.ClientRepository
import com.gestoreasy.services.*
import kotlinx.coroutines.launch

/**
 * Activity para cadastro/edição de cliente
 * Inclui busca automática por CNPJ, CEP e captura de GPS
 */
class ClientFormActivity : AppCompatActivity() {
    private lateinit var binding: ActivityClientFormBinding
    private lateinit var app: MobileApp
    private lateinit var clientRepository: ClientRepository
    private lateinit var cnpjService: CnpjService
    private lateinit var cepService: CepService
    private lateinit var locationService: LocationService
    
    private var clientId: Long? = null
    
    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted: Boolean ->
        if (isGranted) {
            captureLocation()
        } else {
            Toast.makeText(this, "Permissão de localização necessária", Toast.LENGTH_SHORT).show()
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityClientFormBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        app = MobileApp.get(this)
        clientRepository = ClientRepository(app.database.clientDao())
        cnpjService = CnpjService()
        cepService = CepService()
        locationService = LocationService(this)
        
        clientId = intent.getLongExtra("client_id", -1).takeIf { it != -1L }
        
        setupViews()
        if (clientId != null) {
            loadClient()
        }
    }
    
    private fun setupViews() {
        // Busca por CNPJ
        binding.editCnpj.setOnFocusChangeListener { view, hasFocus ->
            if (!hasFocus && view.text.toString().length >= 14) {
                searchCnpj(view.text.toString())
            }
        }
        
        // Botão buscar CNPJ
        binding.btnSearchCnpj.setOnClickListener {
            val cnpj = binding.editCnpj.text.toString()
            if (cnpj.length >= 14) {
                searchCnpj(cnpj)
            }
        }
        
        // Busca por CEP
        binding.editCep.setOnFocusChangeListener { view, hasFocus ->
            if (!hasFocus && view.text.toString().length >= 8) {
                searchCep(view.text.toString())
            }
        }
        
        // Botão buscar CEP
        binding.btnSearchCep.setOnClickListener {
            val cep = binding.editCep.text.toString()
            if (cep.length >= 8) {
                searchCep(cep)
            }
        }
        
        // Botão capturar localização
        binding.btnCaptureLocation.setOnClickListener {
            if (locationService.hasLocationPermission()) {
                captureLocation()
            } else {
                requestPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
            }
        }
        
        // Botão salvar
        binding.btnSave.setOnClickListener {
            saveClient()
        }
    }
    
    private fun searchCnpj(cnpj: String) {
        lifecycleScope.launch {
            try {
                val client = cnpjService.searchCnpj(cnpj)
                if (client != null) {
                    fillForm(client)
                    Toast.makeText(this@ClientFormActivity, "Dados encontrados!", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this@ClientFormActivity, "CNPJ não encontrado", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                Toast.makeText(this@ClientFormActivity, "Erro ao buscar CNPJ: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    private fun searchCep(cep: String) {
        lifecycleScope.launch {
            try {
                val address = cepService.searchCep(cep)
                if (address != null) {
                    binding.editEndereco.setText(address.logradouro)
                    binding.editBairro.setText(address.bairro)
                    binding.editCidade.setText(address.cidade)
                    binding.editEstado.setText(address.estado)
                    binding.editCep.setText(address.cep)
                    Toast.makeText(this@ClientFormActivity, "Endereço encontrado!", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this@ClientFormActivity, "CEP não encontrado", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                Toast.makeText(this@ClientFormActivity, "Erro ao buscar CEP: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    private fun captureLocation() {
        lifecycleScope.launch {
            try {
                val location = locationService.getCurrentLocation()
                if (location != null) {
                    // Salvar coordenadas (serão salvas junto com o cliente)
                    // Por enquanto, apenas mostrar
                    Toast.makeText(
                        this@ClientFormActivity,
                        "Localização capturada: ${location.latitude}, ${location.longitude}",
                        Toast.LENGTH_SHORT
                    ).show()
                } else {
                    Toast.makeText(this@ClientFormActivity, "Não foi possível obter localização", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                Toast.makeText(this@ClientFormActivity, "Erro ao capturar localização: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    private fun fillForm(client: Client) {
        binding.editNome.setText(client.nome)
        binding.editCnpj.setText(client.cpf_cnpj)
        binding.editEmail.setText(client.email)
        binding.editTelefone.setText(client.telefone)
        binding.editEndereco.setText(client.endereco)
        binding.editCidade.setText(client.cidade)
        binding.editEstado.setText(client.estado)
        binding.editCep.setText(client.cep)
    }
    
    private fun loadClient() {
        lifecycleScope.launch {
            // TODO: Carregar cliente do banco
        }
    }
    
    private fun saveClient() {
        lifecycleScope.launch {
            try {
                val nome = binding.editNome.text.toString()
                val cnpj = binding.editCnpj.text.toString()
                val email = binding.editEmail.text.toString()
                val telefone = binding.editTelefone.text.toString()
                val endereco = binding.editEndereco.text.toString()
                val bairro = binding.editBairro.text.toString()
                val cidade = binding.editCidade.text.toString()
                val estado = binding.editEstado.text.toString()
                val cep = binding.editCep.text.toString()
                
                // Capturar localização antes de salvar
                val location = locationService.getCurrentLocation()
                
                val enderecoCompleto = if (bairro.isNotEmpty()) {
                    "$endereco, $bairro"
                } else {
                    endereco
                }
                
                val client = Client(
                    id = clientId ?: 0,
                    nome = nome,
                    tipo = if (cnpj.length == 14) "J" else "F",
                    cpf_cnpj = cnpj.takeIf { it.isNotEmpty() },
                    email = email.takeIf { it.isNotEmpty() },
                    telefone = telefone.takeIf { it.isNotEmpty() },
                    endereco = enderecoCompleto.takeIf { it.isNotEmpty() },
                    cidade = cidade.takeIf { it.isNotEmpty() },
                    estado = estado.takeIf { it.isNotEmpty() },
                    cep = cep.takeIf { it.isNotEmpty() },
                    latitude = location?.latitude,
                    longitude = location?.longitude
                )
                
                if (clientId != null) {
                    clientRepository.update(client)
                } else {
                    clientRepository.insert(client)
                }
                
                Toast.makeText(this@ClientFormActivity, "Cliente salvo com sucesso!", Toast.LENGTH_SHORT).show()
                finish()
            } catch (e: Exception) {
                Toast.makeText(this@ClientFormActivity, "Erro ao salvar: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

