package com.narutohuo.xindazhou.user.ui.login

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.google.android.material.button.MaterialButton
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.textfield.TextInputEditText
import com.narutohuo.xindazhou.R
import com.narutohuo.xindazhou.common.dialog.ServerConfigDialog
import com.narutohuo.xindazhou.share.factory.ShareServiceFactory
import com.narutohuo.xindazhou.share.model.ShareContent
import com.narutohuo.xindazhou.share.model.ShareResponse
import com.narutohuo.xindazhou.user.ui.constant.UiConstants
import com.narutohuo.xindazhou.user.ui.viewmodel.LoginViewModel
import com.narutohuo.xindazhou.user.ui.viewmodel.LoginState
import com.narutohuo.xindazhou.user.ui.viewmodel.LoginViewModelFactory
import kotlinx.coroutines.launch

/**
 * 登录Fragment
 */
class LoginFragment : Fragment() {
    
    private val viewModel: LoginViewModel by viewModels { 
        LoginViewModelFactory(requireContext().applicationContext as android.app.Application)
    }
    
    private lateinit var etMobile: TextInputEditText
    private lateinit var etPassword: TextInputEditText
    private lateinit var btnLogin: MaterialButton
    private lateinit var btnRegister: MaterialButton
    private lateinit var ivServerConfig: View
    private lateinit var progressBar: View
    private lateinit var fabShare: FloatingActionButton
    
    // 延迟初始化，避免在 Fragment 构造函数中调用 ARouter（此时可能还未完全初始化）
    private val shareService by lazy { ShareServiceFactory.getInstance() }
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_login, container, false)
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        etMobile = view.findViewById(R.id.etMobile)
        etPassword = view.findViewById(R.id.etPassword)
        btnLogin = view.findViewById(R.id.btnLogin)
        btnRegister = view.findViewById(R.id.btnRegister)
        ivServerConfig = view.findViewById(R.id.ivServerConfig)
        progressBar = view.findViewById(R.id.progressBar)
        fabShare = view.findViewById(R.id.fabShare)
        
        // 登录按钮
        btnLogin.setOnClickListener {
            val mobile = etMobile.text?.toString()?.trim() ?: ""
            val password = etPassword.text?.toString() ?: ""
            
            if (TextUtils.isEmpty(mobile)) {
                Toast.makeText(requireContext(), UiConstants.MSG_MOBILE_EMPTY, Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            
            if (TextUtils.isEmpty(password)) {
                Toast.makeText(requireContext(), UiConstants.MSG_PASSWORD_EMPTY, Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            
            viewModel.login(mobile, password)
        }
        
        // 注册按钮
        btnRegister.setOnClickListener {
            findNavController().navigate(R.id.action_loginFragment_to_registerFragment)
        }
        
        // 服务器配置按钮
        ivServerConfig.setOnClickListener {
            val dialog = ServerConfigDialog()
            dialog.show(parentFragmentManager, "ServerConfigDialog")
        }
        
        // 分享按钮（测试用）
        fabShare.setOnClickListener {
            testShare()
        }
        
        // 观察登录状态
        lifecycleScope.launch {
            viewModel.loginState.collect { state ->
                when (state) {
                    is LoginState.Idle -> {
                        progressBar.visibility = View.GONE
                        btnLogin.isEnabled = true
                    }
                    is LoginState.Loading -> {
                        progressBar.visibility = View.VISIBLE
                        btnLogin.isEnabled = false
                    }
                    is LoginState.Success -> {
                        progressBar.visibility = View.GONE
                        btnLogin.isEnabled = true
                        Toast.makeText(requireContext(), state.message, Toast.LENGTH_SHORT).show()
                        // 导航到主界面
                        findNavController().navigate(R.id.action_loginFragment_to_mainFragment)
                    }
                    is LoginState.Error -> {
                        progressBar.visibility = View.GONE
                        btnLogin.isEnabled = true
                        Toast.makeText(requireContext(), state.message, Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }
    
    /**
     * 测试分享功能
     */
    private fun testShare() {
        val content = ShareContent.builder()
            .setTitle("新大洲智能车控")
            .setDescription("分享给您一个有趣的内容，这是分享功能测试")
            .setUrl("https://www.xindazhou.com")
            .build()
        
        shareService.share(requireActivity(), content) { response: ShareResponse ->
            if (response.success) {
                val platform = response.data
                Toast.makeText(
                    requireContext(),
                    "分享成功: ${platform?.name ?: "未知平台"}",
                    Toast.LENGTH_SHORT
                ).show()
            } else {
                Toast.makeText(
                    requireContext(),
                    "分享失败: ${response.errorMessage}",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }
}

