package com.rugvedsarika.privatelog.ui.settings

import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.rugvedsarika.privatelog.R
import com.rugvedsarika.privatelog.databinding.FragmentSettingsBinding

import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch

class SettingsFragment : Fragment(R.layout.fragment_settings) {

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        _binding = FragmentSettingsBinding.bind(view)
        
        
        binding.btnBackup.setOnClickListener {
            createDocument.launch("privatelog_backup.enc")
        }
        
        binding.btnRestore.setOnClickListener {
            openDocument.launch(arrayOf("application/octet-stream"))
        }

        binding.btnChangePin.setOnClickListener {
            showChangePinDialog()
        }
    }

    private fun showChangePinDialog() {
        val inputLayout = android.widget.LinearLayout(requireContext())
        inputLayout.orientation = android.widget.LinearLayout.VERTICAL
        inputLayout.setPadding(50, 40, 50, 10)

        val oldPinInput = android.widget.EditText(requireContext())
        oldPinInput.hint = "Old PIN"
        oldPinInput.inputType = android.text.InputType.TYPE_CLASS_NUMBER or android.text.InputType.TYPE_NUMBER_VARIATION_PASSWORD
        inputLayout.addView(oldPinInput)

        val newPinInput = android.widget.EditText(requireContext())
        newPinInput.hint = "New PIN"
        newPinInput.inputType = android.text.InputType.TYPE_CLASS_NUMBER or android.text.InputType.TYPE_NUMBER_VARIATION_PASSWORD
        inputLayout.addView(newPinInput)

        android.app.AlertDialog.Builder(requireContext())
            .setTitle("Change PIN")
            .setView(inputLayout)
            .setPositiveButton("Update") { _, _ ->
                val oldPin = oldPinInput.text.toString()
                val newPin = newPinInput.text.toString()
                
                val prefs = com.rugvedsarika.privatelog.utils.PreferenceHelper(requireContext())
                val storedPin = prefs.getPin()
                
                if (storedPin == oldPin) {
                    if (newPin.isNotEmpty() && newPin.length >= 4) {
                        prefs.savePin(newPin)
                        android.widget.Toast.makeText(requireContext(), "PIN Updated Successfully", android.widget.Toast.LENGTH_SHORT).show()
                    } else {
                        android.widget.Toast.makeText(requireContext(), "New PIN must be at least 4 digits", android.widget.Toast.LENGTH_SHORT).show()
                    }
                } else {
                    android.widget.Toast.makeText(requireContext(), "Incorrect Old PIN", android.widget.Toast.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton("Cancel", null)
            .show()
    }
    
    private val openDocument = registerForActivityResult(androidx.activity.result.contract.ActivityResultContracts.OpenDocument()) { uri ->
        if (uri != null) {
            performRestore(uri)
        }
    }
    
    private val createDocument = registerForActivityResult(androidx.activity.result.contract.ActivityResultContracts.CreateDocument("application/octet-stream")) { uri ->
        if (uri != null) {
            performBackup(uri)
        }
    }
    
    // ...

    private fun performRestore(uri: android.net.Uri) {
         val repo = (requireActivity().application as com.rugvedsarika.privatelog.PrivateLogApp).repository
         val helper = com.rugvedsarika.privatelog.utils.BackupHelper(requireContext(), repo)
         
         lifecycleScope.launch {
            try {
                helper.restoreData(uri)
                android.widget.Toast.makeText(requireContext(), "Restore successful", android.widget.Toast.LENGTH_SHORT).show()
            } catch (e: Exception) {
                e.printStackTrace()
                android.widget.Toast.makeText(requireContext(), "Restore failed", android.widget.Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun performBackup(uri: android.net.Uri) {
        val repo = (requireActivity().application as com.rugvedsarika.privatelog.PrivateLogApp).repository
        val helper = com.rugvedsarika.privatelog.utils.BackupHelper(requireContext(), repo)
        
        lifecycleScope.launch {
            try {
                helper.backupData(uri)
                android.widget.Toast.makeText(requireContext(), "Backup successful", android.widget.Toast.LENGTH_SHORT).show()
            } catch (e: Exception) {
                e.printStackTrace()
                android.widget.Toast.makeText(requireContext(), "Backup failed", android.widget.Toast.LENGTH_SHORT).show()
            }
        }
    }

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