package com.divya.keyspeed.ui

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import com.divya.keyspeed.R
import com.divya.keyspeed.databinding.FragmentTypingBinding
import com.divya.keyspeed.viewmodel.TypingViewModel

class TypingFragment : Fragment() {

    private var _binding: FragmentTypingBinding? = null
    private val binding get() = _binding!!
    
    private val viewModel: TypingViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentTypingBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        if (viewModel.testState.value == 0) {
            val duration = arguments?.getInt("duration") ?: 60
            viewModel.setDuration(duration)
        }

        setupObservers()
        setupListeners()
    }
    
    private fun setupObservers() {
        viewModel.passage.observe(viewLifecycleOwner) { passage ->
            updatePassageHighlight("")
        }
        
        viewModel.timeLeft.observe(viewLifecycleOwner) { seconds ->
            binding.tvTimer.text = "${seconds}s"
        }
        
        viewModel.wpm.observe(viewLifecycleOwner) { wpm ->
            binding.tvLiveWpm.text = "$wpm WPM"
        }
        
        viewModel.testState.observe(viewLifecycleOwner) { state ->
            if (state == 2 && findNavController().currentDestination?.id == R.id.typingFragment) {
                hideKeyboard()
                viewModel.saveResultToHistory()
                val result = viewModel.getFinalResult()
                val bundle = bundleOf("result" to result)
                findNavController().navigate(R.id.action_typingFragment_to_resultFragment, bundle)
            }
        }
    }

    private fun updatePassageHighlight(input: String) {
        val passage = viewModel.passage.value ?: return
        val spannable = android.text.SpannableString(passage)
        
        for (i in passage.indices) {
            val color = when {
                i < input.length -> {
                    if (input[i] == passage[i]) {
                        android.graphics.Color.parseColor("#4CAF50") // Green for correct
                    } else {
                        android.graphics.Color.parseColor("#F44336") // Red for wrong
                    }
                }
                else -> android.graphics.Color.parseColor("#808080") // Gray for untyped
            }
            spannable.setSpan(
                android.text.style.ForegroundColorSpan(color),
                i, i + 1,
                android.text.Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }
        binding.tvPassage.text = spannable
    }

    private fun hideKeyboard() {
        val imm = requireContext().getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as android.view.inputmethod.InputMethodManager
        imm.hideSoftInputFromWindow(binding.etInput.windowToken, 0)
    }
    
    private fun setupListeners() {
        binding.btnBack.setOnClickListener {
            findNavController().popBackStack()
        }

        binding.etInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                val input = s.toString()
                viewModel.onTyping(input)
                updatePassageHighlight(input)
            }
            override fun afterTextChanged(s: Editable?) {}
        })
    }

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