package com.divya.keyspeed.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.divya.keyspeed.R
import com.divya.keyspeed.databinding.FragmentResultBinding
import com.divya.keyspeed.model.TypingResult

class ResultFragment : Fragment() {

    private var _binding: FragmentResultBinding? = null
    private val binding get() = _binding!!
    private var result: TypingResult? = null

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        result = arguments?.getSerializable("result") as? TypingResult
        
        result?.let {
            binding.tvWpm.text = it.wpm.toString()
            binding.tvAccuracy.text = "${it.accuracy}%"
            binding.tvChars.text = "${it.correctChars}/${it.incorrectChars}"
        }
        
        binding.btnRetry.setOnClickListener {
            // Restart with same duration
            val duration = result?.durationSeconds ?: 60
            val bundle = bundleOf("duration" to duration)
            // Navigate back to typing fragment, popping result from stack
            findNavController().navigate(R.id.action_resultFragment_to_typingFragment, bundle)
        }
        
        binding.btnHome.setOnClickListener {
            findNavController().navigate(R.id.action_resultFragment_to_homeFragment)
        }

        binding.btnBack.setOnClickListener {
            findNavController().navigate(R.id.action_resultFragment_to_homeFragment)
        }
    }

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