package com.example.cmpt362_group30_maze_game

import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.SwitchCompat
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import com.example.cmpt362_group30_maze_game.leaderboard.LeaderboardViewModel

class Dialogs : DialogFragment() {

    companion object {
        // Which dialog to show
        const val DIALOG_ARG_KEY = "dialogArgKey"
        const val TOTAL_TIME_ARG_KEY = "totalTime"
        const val DIFFICULTY_ARG_KEY = "difficulty"

        // Only 3 dialogs remain
        const val PAUSE = 1
        const val VICTORY = 2
        const val GAME_OVER = 3
        const val TILT_INTRO = 4

        const val PAUSE_DIALOG_TAG = "Pause Dialog"
        const val VICTORY_DIALOG_TAG = "Victory Dialog"
        const val GAME_OVER_DIALOG_TAG = "Game Over Dialog"
        const val TILT_INTRO_TAG = "Tilt Intro Dialog"
    }

    // parent activity should set the dialog's callback function to the function contained in this
    // interface, to be called when this dialog is dismissed
    interface DialogDismissListener {
        fun onDialogDismissed()
    }

    // the callback function contained in this variable is set by the parent activity to execute
    // logic when the dialog is dismissed
    // this class calls this callback function when the dialog is dismissed
    var dialogDismissedCallback: DialogDismissListener? = null

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val builder = AlertDialog.Builder(requireActivity())
        val dialogId = arguments?.getInt(DIALOG_ARG_KEY)

        return when (dialogId) {
            PAUSE -> createPauseDialog(builder)
            VICTORY -> createVictoryDialog(builder)
            GAME_OVER -> createGameOverDialog(builder)
            TILT_INTRO -> createTiltIntroDialog(builder)
            else -> builder.create()
        }
    }

    // ---------------------------
    // PAUSE DIALOG
    // ---------------------------
    private fun createPauseDialog(builder: AlertDialog.Builder): Dialog {
        val view = requireActivity().layoutInflater.inflate(R.layout.dialog_pause, null)
        builder.setView(view)

        val dialog = builder.create()
        dialog.setCanceledOnTouchOutside(false)

        view.findViewById<Button>(R.id.resumeGameButton).setOnClickListener {
            dialog.dismiss()
            dialogDismissedCallback?.onDialogDismissed()
        }

        view.findViewById<Button>(R.id.quitGameButton).setOnClickListener {
            val intent = Intent(requireActivity(), MainActivity::class.java)
            startActivity(intent)
        }

        return dialog
    }

    // ---------------------------
    // VICTORY DIALOG
    // ---------------------------
    private fun createVictoryDialog(builder: AlertDialog.Builder): Dialog {
        val view = requireActivity().layoutInflater.inflate(R.layout.dialog_victory, null)
        builder.setView(view)

        val prefs = requireActivity().getSharedPreferences(
            SettingsActivity.PREFS_NAME, Context.MODE_PRIVATE
        )

        val name = prefs.getString(SettingsActivity.KEY_NAME, "Anonymous")!!
        val time = arguments?.getInt(TOTAL_TIME_ARG_KEY) ?: 0
        val difficulty = arguments?.getInt(DIFFICULTY_ARG_KEY) ?: 0

        view.findViewById<TextView>(R.id.total_time).text = "Your time: $time seconds"
        view.findViewById<TextView>(R.id.player_name).text = "Player name: $name"

        val leaderboardEnabled = prefs.getBoolean(SettingsActivity.KEY_LEADERBOARD, false)
        val switch = view.findViewById<SwitchCompat>(R.id.post_to_leaderboard_switch)
        switch.isChecked = leaderboardEnabled

        view.findViewById<Button>(R.id.exit_button).setOnClickListener {
            if (switch.isChecked) {
                val vm = ViewModelProvider(this)[LeaderboardViewModel::class.java]
                vm.insertNewRun(name, time, difficulty)
                Toast.makeText(requireActivity(), "Entry added to leaderboard", Toast.LENGTH_SHORT).show()
            }

            val intent = Intent(requireActivity(), MainActivity::class.java)
            startActivity(intent)
        }

        val dialog = builder.create()
        dialog.setCanceledOnTouchOutside(false)
        return dialog
    }

    // ---------------------------
    // GAME OVER DIALOG
    // ---------------------------
    private fun createGameOverDialog(builder: AlertDialog.Builder): Dialog {
        val view = requireActivity().layoutInflater.inflate(R.layout.dialog_gameover, null)
        builder.setView(view)

        view.findViewById<Button>(R.id.exit_button).setOnClickListener {
            val intent = Intent(requireActivity(), MainActivity::class.java)
            startActivity(intent)
        }

        val dialog = builder.create()
        dialog.setCanceledOnTouchOutside(false)
        return dialog
    }

    // ---------------------------
    // TILT INSTRUCTIONS INTRO DIALOG
    // ---------------------------
    private fun createTiltIntroDialog(builder: AlertDialog.Builder): Dialog {
        val message = """
            Inertial Control Guide

            • Gently flick the phone forward to accelerate the submarine.
            • Flick the phone backward gradually to slow down or move back.
            • Rotate the phone left or right to turn the submarine.
            • Keep your movements smooth – the submarine follows your flicks and rotations.
        """.trimIndent()

        val dialog = builder
            .setTitle("How to Control the Submarine")
            .setMessage(message)
            .setPositiveButton("Close", { dialog, which ->
                dialogDismissedCallback?.onDialogDismissed()
                dialog.dismiss()
            })
            .create()

        dialog.setCanceledOnTouchOutside(false)

        return dialog
    }
}
