package com.kaixed.kchat.ui.fragment

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.Window
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import com.kaixed.kchat.databinding.DialogDeleteContactBinding

class DeleteContactDialogFragment : DialogFragment() {

    interface OnContactDeletedListener {
        fun onContactDeleted()
    }

    private lateinit var contactId: String
    private var listener: OnContactDeletedListener? = null

    companion object {
        fun newInstance(contactId: String): DeleteContactDialogFragment {
            val fragment = DeleteContactDialogFragment()
            val args = Bundle()
            args.putString("contactId", contactId)
            fragment.arguments = args
            return fragment
        }
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is OnContactDeletedListener) {
            listener = context
        } else {
            throw RuntimeException("$context must implement OnContactDeletedListener")
        }
    }

    override fun onDetach() {
        super.onDetach()
        listener = null
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        contactId = arguments?.getString("contactId") ?: ""

        val binding = DialogDeleteContactBinding.inflate(layoutInflater)
        val dialog = Dialog(requireContext())
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setCancelable(false)
        dialog.setContentView(binding.root)
        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

        val layoutParams = WindowManager.LayoutParams().apply {
            copyFrom(dialog.window?.attributes)
            width = (requireContext().resources.displayMetrics.widthPixels * 0.8).toInt()
            gravity = Gravity.CENTER
        }
        dialog.window?.attributes = layoutParams

        binding.tvCancel.setOnClickListener {
            dialog.dismiss()
        }

        binding.tvDelete.setOnClickListener {
            listener?.onContactDeleted()
            dialog.dismiss()
        }
        return dialog
    }
}
