package ru.myitschool.work.ui.main

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.squareup.picasso.Picasso
import dagger.hilt.android.AndroidEntryPoint
import ru.myitschool.work.R
import ru.myitschool.work.databinding.FragmentMainBinding
import ru.myitschool.work.ui.list.ListAdapter
import ru.myitschool.work.ui.login.LoginDestination
import ru.myitschool.work.ui.scan.qr.QrScanDestination
import ru.myitschool.work.utils.AuthPreferences
import ru.myitschool.work.utils.collectWhenStarted
import ru.myitschool.work.utils.visibleOrGone
import java.util.Locale

@AndroidEntryPoint
class MainFragment : Fragment(R.layout.fragment_main) {
    private var _binding: FragmentMainBinding? = null
    private val binding: FragmentMainBinding get() = _binding!!
    private lateinit var authPreferences: AuthPreferences
    private val viewModel: MainViewModel by viewModels()
    private lateinit var listAdapter: ListAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        authPreferences = AuthPreferences(requireContext())

        if (!authPreferences.isLoggedIn()) {
            navigateToLogin()
        }
    }

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

        setupRecyclerView()


        if (authPreferences.isLoggedIn()) {
            setupMainComponents()

            observeUserState()
            observeListState()

            viewModel.getUserData(authPreferences.getLogin() ?: "")

            val login = authPreferences.getLogin().toString()
            viewModel.loadList(login)
        }
    }

    private fun hideAll() {
        binding.apply {
            username.visibleOrGone(false)
            position.visibleOrGone(false)
            lastEntry.visibleOrGone(false)
            scan.visibleOrGone(false)
            logout.visibleOrGone(false)

            error.visibleOrGone(true)
            refresh.visibleOrGone(true)
        }
    }

    private fun setupRecyclerView() {
        listAdapter = ListAdapter()
        binding.entranceData.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = listAdapter
            addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
        }
    }

    private fun observeUserState() {
        viewModel.state.collectWhenStarted(this) { state ->
            when (state) {
                is MainViewModel.MainState.Initial -> {
                    binding.error.visibleOrGone(false)
                }
                is MainViewModel.MainState.Loading -> {
                    binding.error.visibleOrGone(false)
                }
                is MainViewModel.MainState.Success -> {
                    binding.apply {
                        username.visibleOrGone(true)
                        position.visibleOrGone(true)
                        lastEntry.visibleOrGone(true)
                        scan.visibleOrGone(true)
                        logout.visibleOrGone(true)
                        error.visibleOrGone(false)

                        username.text = state.userInfo.name
                        position.text = state.userInfo.position

                        loadImageFromUrl(state.userInfo.photoUrl)

                        val inputFormat = java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault())
                        val outputFormat = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())

                        try {
                            val parsedDate = inputFormat.parse(state.userInfo.lastVisit)
                            lastEntry.text = parsedDate?.let { outputFormat.format(it) } ?: state.userInfo.lastVisit
                        } catch (e: Exception) {
                            lastEntry.text = state.userInfo.lastVisit
                        }
                    }
                }
                is MainViewModel.MainState.Error -> {
                    hideAll()
                    binding.error.text = state.message
                }
            }
        }
    }

    private fun observeListState() {
        viewModel.listState.collectWhenStarted(this) { state ->
            when (state) {
                is MainViewModel.ListState.Loading -> {
                    //TODO
                }
                is MainViewModel.ListState.Success -> {
                    listAdapter.submitList(state.data)
                }
                is MainViewModel.ListState.Error -> {
                    //TODO
                    binding.error.text = state.message
                }
            }
        }
    }

    private fun loadImageFromUrl(url: String) {
        Picasso
            .get()
            .load(url)
            .error(R.drawable.icon_profile)
            .into(binding.photo)
    }

    private fun setupMainComponents() {
        binding.logout.setOnClickListener {
            authPreferences.clearLoginState()
            navigateToLogin()
        }

        binding.refresh.setOnClickListener {
            viewModel.getUserData(authPreferences.getLogin() ?: "")
        }

        binding.scan.setOnClickListener {
            findNavController().navigate(QrScanDestination)
        }
    }

    private fun navigateToLogin() {
        try {
            authPreferences.clearLoginState()
            findNavController().apply {
                popBackStack(LoginDestination, false)
                navigate(LoginDestination)
            }
        } catch (e: Exception) {
            Log.e("MainFragment", "Error navigating to login", e)
        }
    }

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