package com.rugvedsarika.toolbox.utilities

import android.content.ClipboardManager
import android.content.ClipData
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.core.os.bundleOf
import com.rugvedsarika.toolbox.R
import com.rugvedsarika.toolbox.databinding.FragmentPasswordGeneratorBinding
import java.security.SecureRandom

class PasswordGeneratorFragment : Fragment() {

    private var _binding: FragmentPasswordGeneratorBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentPasswordGeneratorBinding.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 "password_generator")
                    )
                    true
                }
                else -> false
            }
        }

        binding.sliderLength.addOnChangeListener { _, value, _ ->
            binding.tvLengthLabel.text = "Password Length: ${value.toInt()}"
        }
        binding.tvLengthLabel.text = "Password Length: ${binding.sliderLength.value.toInt()}"

        binding.btnGenerate.setOnClickListener {
            generatePassword()
        }

        binding.btnCopy.setOnClickListener {
            copyToClipboard()
        }

        // Initial generation
        generatePassword()
    }

    private fun generatePassword() {
        val length = binding.sliderLength.value.toInt()
        val includeUpper = binding.cbUppercase.isChecked
        val includeDigits = binding.cbDigits.isChecked
        val includeSymbols = binding.cbSymbols.isChecked

        val lowercase = "abcdefghijklmnopqrstuvwxyz"
        val uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        val digits = "0123456789"
        val symbols = "!@#$%^&*()_+-=[]{}|;:,.<>?"

        var charPool = lowercase
        if (includeUpper) charPool += uppercase
        if (includeDigits) charPool += digits
        if (includeSymbols) charPool += symbols

        val random = SecureRandom()
        val password = StringBuilder()

        for (i in 0 until length) {
            val randomIndex = random.nextInt(charPool.length)
            password.append(charPool[randomIndex])
        }

        binding.tvPassword.text = password.toString()
    }

    private fun copyToClipboard() {
        val password = binding.tvPassword.text.toString()
        val clipboard = requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        val clip = ClipData.newPlainText("Generated Password", password)
        clipboard.setPrimaryClip(clip)
        Toast.makeText(requireContext(), "Password copied to clipboard", Toast.LENGTH_SHORT).show()
    }

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