package ru.myitschool.work.ui.result

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import dagger.hilt.android.AndroidEntryPoint
import ru.myitschool.work.R
import ru.myitschool.work.api.scan.CodeJson
import ru.myitschool.work.api.scan.OpenType
import ru.myitschool.work.databinding.FragmentScanResultBinding
import ru.myitschool.work.ui.main.MainDestination
import ru.myitschool.work.utils.AuthPreferences
import ru.myitschool.work.utils.QrPreferences
import ru.myitschool.work.utils.collectWhenStarted
import ru.myitschool.work.utils.getCurrentTime
import ru.myitschool.work.utils.visibleOrGone

@AndroidEntryPoint
class ResultFragment : Fragment(R.layout.fragment_scan_result) {
    private var _binding: FragmentScanResultBinding? = null
    private val binding: FragmentScanResultBinding get() = _binding!!
    private val viewModel: ResultViewModel by viewModels()

    private lateinit var authPreferences: AuthPreferences
    private lateinit var qrPreferences: QrPreferences

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

        authPreferences = AuthPreferences(requireContext())
        qrPreferences = QrPreferences(requireContext())

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        _binding = FragmentScanResultBinding.bind(view)

        setupOpenComponents()
        observeOpenState()
    }

    private fun setupOpenComponents() {
        binding.apply {
            result.visibleOrGone(false)
            successIcon.visibleOrGone(false)

            close.setOnClickListener {
                navigateToResultScreen()
            }
        }

        val qrData = qrPreferences.getQr()

        if (qrData != null) {
            authPreferences.getLogin()?.let { login ->
                val currentTime = getCurrentTime()
                viewModel.open(login, CodeJson(
                    value = qrData.toString(),
                    type = OpenType.QR_TYPE,
                    time = currentTime
                ))
            }
        } else {
            Log.e("ResultFragment", "QR data is null")
            Toast.makeText(context, getString(R.string.error), Toast.LENGTH_SHORT).show()
        }
    }

    private fun observeOpenState() {
        viewModel.state.collectWhenStarted(this) { state ->
            when (state) {
                is ResultViewModel.ResultState.Loading -> {
                    binding.result.visibleOrGone(false)
                    binding.successIcon.visibleOrGone(false)
                    binding.error.visibleOrGone(false)
                    binding.loading.visibleOrGone(true)
                }
                is ResultViewModel.ResultState.Success -> {
                    binding.result.visibleOrGone(true)
                    binding.successIcon.visibleOrGone(true)
                    binding.error.visibleOrGone(false)
                    binding.loading.visibleOrGone(false)
                }
                is ResultViewModel.ResultState.InvalidCredentials -> {
                    binding.result.visibleOrGone(false)
                    binding.successIcon.visibleOrGone(false)
                    binding.loading.visibleOrGone(false)
                    binding.error.visibleOrGone(true)
                }
                is ResultViewModel.ResultState.Error -> {
                    binding.loading.visibleOrGone(false)
                    binding.result.apply {
                        visibleOrGone(true)
                        text = getText(R.string.userNotFing)
                    }
                    Log.d("Authentication", getText(R.string.userNotFing).toString())
                }
                ResultViewModel.ResultState.Initial -> binding.loading.visibleOrGone(false)
            }
        }
    }

    private fun navigateToResultScreen() {
        try {
            findNavController().apply {
                popBackStack(MainDestination, false)
                navigate(MainDestination)
            }
        } catch (e: Exception) {
            Log.e("ResultFragment", "Navigation error", e)
            Toast.makeText(context, getText(R.string.errorGoText).toString(), Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroyView() {
        _binding = null
        super.onDestroyView()
    }
}