package com.rugvedsarika.toolbox.utilities

import android.app.DatePickerDialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.rugvedsarika.toolbox.R
import com.rugvedsarika.toolbox.databinding.FragmentAgeCalculatorBinding
import java.util.*

class AgeCalculatorFragment : Fragment() {

    private var _binding: FragmentAgeCalculatorBinding? = null
    private val binding get() = _binding!!
    private var selectedDate: Calendar? = null

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.toolbar.setNavigationOnClickListener {
            findNavController().navigateUp()
        }

        binding.toolbar.setOnMenuItemClickListener { menuItem ->
            when (menuItem.itemId) {
                R.id.action_history -> {
                    findNavController().navigate(
                        R.id.historyFragment,
                        bundleOf("toolId" to "age_calculator")
                    )
                    true
                }
                else -> false
            }
        }

        binding.btnPickDate.setOnClickListener {
            showDatePicker()
        }

        binding.btnCalculateAge.setOnClickListener {
            calculateAge()
        }
    }

    private fun showDatePicker() {
        val calendar = Calendar.getInstance()
        val datePicker = DatePickerDialog(
            requireContext(),
            { _, year, month, dayOfMonth ->
                selectedDate = Calendar.getInstance().apply {
                    set(year, month, dayOfMonth)
                }
                binding.btnPickDate.text = "$dayOfMonth/${month + 1}/$year"
            },
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        )
        datePicker.datePicker.maxDate = System.currentTimeMillis()
        datePicker.show()
    }

    private fun calculateAge() {
        val birthday = selectedDate ?: run {
            Toast.makeText(requireContext(), "Please select a date", Toast.LENGTH_SHORT).show()
            return
        }

        val today = Calendar.getInstance()

        var years = today.get(Calendar.YEAR) - birthday.get(Calendar.YEAR)
        var months = today.get(Calendar.MONTH) - birthday.get(Calendar.MONTH)
        var days = today.get(Calendar.DAY_OF_MONTH) - birthday.get(Calendar.DAY_OF_MONTH)

        if (days < 0) {
            months--
            days += today.getActualMaximum(Calendar.DAY_OF_MONTH)
        }

        if (months < 0) {
            years--
            months += 12
        }

        binding.tvAgeResult.text = "$years Years, $months Months, $days Days"
        
        // Next birthday calculation
        val nextBirthday = Calendar.getInstance().apply {
            set(Calendar.YEAR, today.get(Calendar.YEAR))
            set(Calendar.MONTH, birthday.get(Calendar.MONTH))
            set(Calendar.DAY_OF_MONTH, birthday.get(Calendar.DAY_OF_MONTH))
        }

        if (nextBirthday.before(today) || nextBirthday.equals(today)) {
            nextBirthday.add(Calendar.YEAR, 1)
        }

        val diffMillis = nextBirthday.timeInMillis - today.timeInMillis
        val diffDays = (diffMillis / (1000 * 60 * 60 * 24)).toInt()
        val monthsToBday = diffDays / 30
        val remainingDays = diffDays % 30

        binding.tvExtraInfo.text = "Next birthday in $monthsToBday Months and $remainingDays Days"
        binding.cardResult.visibility = View.VISIBLE
    }

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