package com.rugvedsarika.docscan.ui.preview

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.viewpager2.widget.ViewPager2
import com.rugvedsarika.docscan.data.entity.Document
import com.rugvedsarika.docscan.databinding.FragmentPreviewBinding
import com.rugvedsarika.docscan.ui.adapter.PageAdapter
import com.rugvedsarika.docscan.viewmodel.MainViewModel
import kotlinx.coroutines.launch
import java.io.File

class PreviewFragment : Fragment() {

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

    private val viewModel: MainViewModel by viewModels()
    private val args: PreviewFragmentArgs by navArgs()

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

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

        val document = args.document
        binding.toolbar.title = document.name
        binding.toolbar.setNavigationOnClickListener { findNavController().navigateUp() }

        setupViewPager(document.id)
        setupClickListeners()
    }

    private fun setupClickListeners() {
        binding.btnShare.setOnClickListener {
            shareCurrentPage()
        }
    }

    private fun shareCurrentPage() {
        val currentItem = binding.viewPager.currentItem
        val adapter = binding.viewPager.adapter as? PageAdapter
        val page = adapter?.getPageAt(currentItem) ?: return
        
        val options = arrayOf("Normal Share", "Share with Watermark")
        android.app.AlertDialog.Builder(requireContext())
            .setTitle("Share Options")
            .setItems(options) { _, which ->
                if (which == 1) {
                    showWatermarkDialog(page.imagePath)
                } else {
                    performShare(File(page.imagePath))
                }
            }.show()
    }

    private fun showWatermarkDialog(imagePath: String) {
        val input = android.widget.EditText(requireContext())
        input.hint = "Enter watermark text"
        
        android.app.AlertDialog.Builder(requireContext())
            .setTitle("Custom Watermark")
            .setView(input)
            .setPositiveButton("Share") { _, _ ->
                val text = input.text.toString()
                if (text.isNotEmpty()) {
                    val watermarkedFile = applyWatermark(imagePath, text)
                    performShare(watermarkedFile)
                }
            }
            .setNegativeButton("Cancel", null)
            .show()
    }

    private fun applyWatermark(imagePath: String, text: String): File {
        val bitmap = android.graphics.BitmapFactory.decodeFile(imagePath)
        val mutableBitmap = bitmap.copy(android.graphics.Bitmap.Config.ARGB_8888, true)
        val canvas = android.graphics.Canvas(mutableBitmap)
        val paint = android.graphics.Paint().apply {
            color = android.graphics.Color.RED
            alpha = 120
            textSize = (mutableBitmap.width / 10).toFloat()
            isAntiAlias = true
        }
        
        canvas.drawText(text, 50f, (mutableBitmap.height / 2).toFloat(), paint)
        
        val file = File(requireContext().cacheDir, "wm_${System.currentTimeMillis()}.jpg")
        java.io.FileOutputStream(file).use { out ->
            mutableBitmap.compress(android.graphics.Bitmap.CompressFormat.JPEG, 90, out)
        }
        return file
    }

    private fun performShare(file: File) {
        val uri = androidx.core.content.FileProvider.getUriForFile(
            requireContext(),
            "${requireActivity().packageName}.provider",
            file
        )
        val intent = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
            type = "image/jpeg"
            putExtra(android.content.Intent.EXTRA_STREAM, uri)
            addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
        startActivity(android.content.Intent.createChooser(intent, "Share Image"))
    }

    private fun setupViewPager(documentId: Long) {
        lifecycleScope.launch {
            viewModel.getPagesForDocument(documentId).collect { pages ->
                val adapter = PageAdapter(pages)
                binding.viewPager.adapter = adapter
                
                binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                    override fun onPageSelected(position: Int) {
                        binding.tvPageIndicator.text = "${position + 1} / ${pages.size}"
                    }
                })
                
                if (pages.isNotEmpty()) {
                    binding.tvPageIndicator.text = "1 / ${pages.size}"
                }
            }
        }
    }

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