package com.rugvedsarika.landarea.ui

import android.content.Intent
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 android.widget.ArrayAdapter
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.rugvedsarika.landarea.databinding.FragmentConverterBinding

class ConverterFragment : Fragment() {

    private var _binding: FragmentConverterBinding? = null
    private val binding get() = _binding!!
    private val viewModel: MainViewModel by viewModels({ requireActivity() })

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupInput()
        setupSpinners()
        setupButtons()
        observeViewModel()
    }

    private fun setupInput() {
        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) {
                viewModel.onInputValueChanged(s.toString())
            }
            override fun afterTextChanged(s: Editable?) {}
        })
    }

    private fun setupSpinners() {
        val unitAdapter = ArrayAdapter(requireContext(), android.R.layout.simple_dropdown_item_1line, viewModel.units)
        binding.spinnerFrom.setAdapter(unitAdapter)
        binding.spinnerTo.setAdapter(unitAdapter)

        val stateAdapter = ArrayAdapter(requireContext(), android.R.layout.simple_dropdown_item_1line, viewModel.states)
        binding.spinnerState.setAdapter(stateAdapter)

        binding.spinnerFrom.setOnItemClickListener { _, _, position, _ ->
            viewModel.onFromUnitChanged(viewModel.units[position])
        }

        binding.spinnerTo.setOnItemClickListener { _, _, position, _ ->
            viewModel.onToUnitChanged(viewModel.units[position])
        }

        binding.spinnerState.setOnItemClickListener { _, _, position, _ ->
            viewModel.onStateChanged(viewModel.states[position])
        }
    }

    private fun setupButtons() {
        binding.btnSwap.setOnClickListener {
            viewModel.swapUnits()
        }

        binding.btnShare.setOnClickListener {
            shareResult()
        }
    }

    private fun observeViewModel() {
        viewModel.inputValue.observe(viewLifecycleOwner) { value ->
            if (binding.etInput.text.toString() != value) {
                binding.etInput.setText(value)
            }
        }

        viewModel.fromUnit.observe(viewLifecycleOwner) { unit ->
            binding.spinnerFrom.setText(unit, false)
        }

        viewModel.toUnit.observe(viewLifecycleOwner) { unit ->
            binding.spinnerTo.setText(unit, false)
            binding.tvResultUnit.text = unit
        }

        viewModel.selectedState.observe(viewLifecycleOwner) { state ->
            binding.spinnerState.setText(state, false)
        }

        viewModel.result.observe(viewLifecycleOwner) { result ->
            binding.tvResult.text = result
        }
    }

    private fun shareResult() {
        val text = "LandArea Result:\n" +
                "${viewModel.inputValue.value} ${viewModel.fromUnit.value}\n" +
                "Equals to: ${viewModel.result.value} ${viewModel.toUnit.value}\n" +
                "(State: ${viewModel.selectedState.value})"
        
        val intent = Intent(Intent.ACTION_SEND).apply {
            type = "text/plain"
            putExtra(Intent.EXTRA_TEXT, text)
        }
        startActivity(Intent.createChooser(intent, "Share via"))
    }

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