package com.narutohuo.xindazhou.user.ui

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.button.MaterialButton
import com.narutohuo.xindazhou.R
import com.narutohuo.xindazhou.common.ui.BaseActivity
import com.narutohuo.xindazhou.databinding.ActivityUserBinding
import com.narutohuo.xindazhou.databinding.FragmentUserSocketTestBinding
import com.narutohuo.xindazhou.community.ui.CommunityActivity
import com.narutohuo.xindazhou.service.ui.ServiceActivity
import com.narutohuo.xindazhou.shop.ui.ShopActivity
import com.narutohuo.xindazhou.user.ui.viewmodel.UserViewModel
import com.narutohuo.xindazhou.user.ui.viewmodel.UserViewModelFactory
import com.narutohuo.xindazhou.vehicle.ui.VehicleActivity
import kotlinx.coroutines.launch

/**
 * 用户 Activity
 * 
 * 架构A：每个页面一个Activity
 * 包含 SocketIO 测试功能
 */
class UserActivity : BaseActivity<ActivityUserBinding>() {
    
    private lateinit var viewModel: UserViewModel
    private lateinit var contentBinding: FragmentUserSocketTestBinding
    
    private lateinit var tvConnectionStatus: TextView
    private lateinit var btnConnect: MaterialButton
    private lateinit var btnFindVehicle: MaterialButton
    private lateinit var tvLog: TextView
    
    override fun getViewBinding(): ActivityUserBinding {
        return ActivityUserBinding.inflate(layoutInflater)
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 初始化 ViewModel
        viewModel = androidx.lifecycle.ViewModelProvider(
            this,
            UserViewModelFactory(application)
        )[UserViewModel::class.java]
        
        // 初始化内容布局
        contentBinding = FragmentUserSocketTestBinding.bind(binding.contentLayout.root)
        
        initViews()
        setupClickListeners()
        observeUiState()
        observeAlarmMessage()
        observeErrorMessage()
    }
    
    override fun initView() {
        // 设置底部导航栏
        setupBottomNavigation()
    }
    
    private fun initViews() {
        tvConnectionStatus = contentBinding.tvConnectionStatus
        btnConnect = contentBinding.btnConnect
        btnFindVehicle = contentBinding.btnFindVehicle
        tvLog = contentBinding.tvLog
    }
    
    private fun setupClickListeners() {
        btnConnect.setOnClickListener {
            if (viewModel.uiState.value.isConnected) {
                viewModel.disconnect()
            } else {
                viewModel.connect()
            }
        }

        btnFindVehicle.setOnClickListener {
            viewModel.sendFindVehicleCommand()
        }
    }
    
    /**
     * 观察 UI 状态（连接状态、日志列表）
     */
    private fun observeUiState() {
        lifecycleScope.launch {
            viewModel.uiState.collect { state ->
                tvConnectionStatus.text = "连接状态：${if (state.isConnected) "已连接" else "未连接"}"
                btnConnect.text = if (state.isConnected) "断开连接" else "连接SocketIO"
                btnFindVehicle.isEnabled = state.isConnected
                tvLog.text = state.logs.joinToString("\n")
                
                tvLog.post {
                    val scrollView = tvLog.parent as? android.widget.ScrollView
                    scrollView?.fullScroll(View.FOCUS_DOWN)
                }
            }
        }
    }

    /**
     * 观察报警消息
     */
    private fun observeAlarmMessage() {
        lifecycleScope.launch {
            viewModel.alarmMessage.collect { alarm ->
                alarm?.let {
                    Toast.makeText(this@UserActivity, "收到车辆报警！", Toast.LENGTH_LONG).show()
                }
            }
        }
    }

    /**
     * 观察错误消息
     */
    private fun observeErrorMessage() {
        lifecycleScope.launch {
            viewModel.errorMessage.collect { error ->
                error?.let {
                    Toast.makeText(this@UserActivity, error, Toast.LENGTH_SHORT).show()
                    viewModel.clearErrorMessage()
                }
            }
        }
    }
    
    private fun setupBottomNavigation() {
        binding.bottomNavView.selectedItemId = R.id.userFragment
        binding.bottomNavView.setOnItemSelectedListener { item ->
            when (item.itemId) {
                R.id.vehicleFragment -> {
                    startActivity(Intent(this, VehicleActivity::class.java))
                    finish()
                    true
                }
                R.id.communityFragment -> {
                    startActivity(Intent(this, CommunityActivity::class.java))
                    finish()
                    true
                }
                R.id.serviceFragment -> {
                    startActivity(Intent(this, ServiceActivity::class.java))
                    finish()
                    true
                }
                R.id.shopFragment -> {
                    startActivity(Intent(this, ShopActivity::class.java))
                    finish()
                    true
                }
                R.id.userFragment -> {
                    // 当前已在用户模块，不需要跳转
                    true
                }
                else -> false
            }
        }
    }
}

