package com.doverfuelingsolutions.issp.view.fragment

import android.content.DialogInterface
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.navigation.fragment.findNavController
import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.data.DataStore
import com.doverfuelingsolutions.issp.databinding.FragmentMainBinding
import com.doverfuelingsolutions.issp.fusion.FusionError
import com.doverfuelingsolutions.issp.fusion.FusionManager
import com.doverfuelingsolutions.issp.fusion.callback.OnFusionEvent
import com.doverfuelingsolutions.issp.utils.StringUtil
import com.doverfuelingsolutions.issp.view.MainActivity
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

class FragmentMain : Fragment(), OnFusionEvent {

    private val globalViewModel: MainActivity.GlobalViewModel by activityViewModels()
    private val mainViewModel: MainViewModel by viewModels()

    private lateinit var binding: FragmentMainBinding
    private val controllerMain: NavController by lazy { Navigation.findNavController(binding.navMain) }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_main, container, false)
        binding.lifecycleOwner = this
        binding.mainViewModel = mainViewModel

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        when (findNavController().currentBackStackEntry?.savedStateHandle?.get<Boolean>(FragmentLogin.KEY_LOGIN_RESULT)) {
            null, true -> {
                globalViewModel.isLogin.observe(viewLifecycleOwner, {
                    if (!it) {
                        findNavController().navigate(R.id.action_fragmentMain_to_fragmentLogin)
                    } else {
                        initView()
                        initFusion()
                    }
                })
            }
            else -> {
                MaterialAlertDialogBuilder(requireContext())
                    .setTitle(resources.getString(R.string.login_tip))
                    .setMessage(R.string.login_tip_detail)
                    .setPositiveButton(resources.getString(R.string.confirm)) { _, _ ->
                        findNavController().navigate(R.id.action_fragmentMain_to_fragmentLogin)
                    }
                    .setNegativeButton(R.string.cancel) { _, _ ->
                        activity?.onBackPressed()
                    }
                    .setCancelable(false)
                    .show()
            }
        }
    }

    override fun onFusionInit(code: FusionError, msg: String) {
        lifecycleScope.launch {
            if (code != FusionError.Success) {
                MaterialAlertDialogBuilder(requireContext())
                    .setTitle(R.string.tip_opt_fail)
                    .setCancelable(false)
                    .setMessage(StringUtil.get(R.string.tip_connect_fail_reason_config, msg))
                    .setPositiveButton(R.string.go_check) { _, _ ->
                        controllerMain.navigate(R.id.action_mainType_to_mainPreference)
                    }
                    .show()
            }
        }
    }

    private fun initView() {
        mainViewModel.stationName.value = DataStore.buName
        if (DataStore.stationLogoFile.isNotEmpty()) binding.stationLogo.setImageURI(Uri.fromFile(File(context?.filesDir, DataStore.stationLogoFile)))
        initBanner()
    }

    private fun initFusion() {
        FusionManager.onFusionEvent = this
        lifecycle.addObserver(FusionManager)
    }

    private fun initBanner() {
        binding.banner.run {
            addBannerLifecycleObserver(this@FragmentMain)
            scrollTime = 500
            adapter =
                object : BannerImageAdapter<Int>(listOf(R.mipmap.banner_1, R.mipmap.banner_2)) {
                    override fun onBindView(holder: BannerImageHolder, data: Int, position: Int, size: Int) {
                        holder.imageView.setImageResource(data)
                    }
                }
        }
    }

    class MainViewModel : ViewModel() {
        val stationName = MutableLiveData("")
    }
}