package com.jordanbot.autoride

import android.graphics.BitmapFactory
import android.media.MediaPlayer
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.ScrollView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.net.URL

class TutorialActivity : AppCompatActivity() {

    private var mediaPlayer: MediaPlayer? = null

    // Tutorial steps: image URL + title + description
    private data class TutorialStep(
        val imageUrl: String,
        val title: String,
        val description: String,
        val titleColor: String
    )

    private val steps = listOf(
        TutorialStep(
            imageUrl = "https://lawer.tripz-egypt.com/jordan_bot/tutorial/step1.png",
            title = "الخطوة ١: ابحث عن التطبيق",
            description = "اذهب إلى إعدادات الهاتف → إدارة التطبيقات → ابحث عن Jordan Bot واضغط عليه.",
            titleColor = "#4CAF50"
        ),
        TutorialStep(
            imageUrl = "https://lawer.tripz-egypt.com/jordan_bot/tutorial/step2.png",
            title = "الخطوة ٢: فك القيود (أهم خطوة!)",
            description = "اضغط على النقاط الثلاث ⋮ في أعلى الصفحة واختر 'السماح بالإعدادات المقيدة' أو 'Allow restricted settings'.",
            titleColor = "#FF5252"
        ),
        TutorialStep(
            imageUrl = "https://lawer.tripz-egypt.com/jordan_bot/tutorial/step3.png",
            title = "الخطوة ٣: فعّل الصلاحية",
            description = "ارجع إلى التطبيق وقم بتفعيل صلاحيات إمكانية الوصول والإشعارات. اضغط 'سماح' عند ظهور التأكيد.",
            titleColor = "#4CAF50"
        )
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_tutorial)

        // Load images from server
        loadTutorialImages()

        // Audio button
        findViewById<Button>(R.id.btn_play_audio).setOnClickListener {
            playTutorialAudio()
        }
    }

    private fun loadTutorialImages() {
        val container = findViewById<LinearLayout>(R.id.tutorial_steps_container)
        container.removeAllViews()

        for (step in steps) {
            // Create step card
            val card = LinearLayout(this).apply {
                orientation = LinearLayout.VERTICAL
                setBackgroundColor(android.graphics.Color.parseColor("#1E1E1E"))
                setPadding(dp(16), dp(16), dp(16), dp(16))
                layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                ).apply { bottomMargin = dp(20) }
            }

            // Title
            val title = TextView(this).apply {
                text = step.title
                setTextColor(android.graphics.Color.parseColor(step.titleColor))
                textSize = 20f
                setTypeface(typeface, android.graphics.Typeface.BOLD)
                setPadding(0, 0, 0, dp(8))
            }
            card.addView(title)

            // Description
            val desc = TextView(this).apply {
                text = step.description
                setTextColor(android.graphics.Color.parseColor("#BBBBBB"))
                textSize = 15f
                setPadding(0, 0, 0, dp(12))
            }
            card.addView(desc)

            // Loading indicator
            val progress = ProgressBar(this).apply {
                layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                ).apply { gravity = android.view.Gravity.CENTER }
            }
            card.addView(progress)

            // Image
            val imageView = ImageView(this).apply {
                layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    dp(350)
                )
                scaleType = ImageView.ScaleType.FIT_CENTER
                setBackgroundColor(android.graphics.Color.parseColor("#2C2C2C"))
                visibility = View.GONE
            }
            card.addView(imageView)

            container.addView(card)

            // Load image async
            CoroutineScope(Dispatchers.IO).launch {
                try {
                    val url = URL(step.imageUrl)
                    val bitmap = BitmapFactory.decodeStream(url.openStream())
                    withContext(Dispatchers.Main) {
                        progress.visibility = View.GONE
                        imageView.setImageBitmap(bitmap)
                        imageView.visibility = View.VISIBLE
                    }
                } catch (e: Exception) {
                    withContext(Dispatchers.Main) {
                        progress.visibility = View.GONE
                        // Image failed to load - text instructions remain visible
                    }
                }
            }
        }
    }

    private fun playTutorialAudio() {
        if (mediaPlayer?.isPlaying == true) {
            mediaPlayer?.stop()
            mediaPlayer?.release()
            mediaPlayer = null
            findViewById<Button>(R.id.btn_play_audio).text = "استمع للشرح الصوتي 🔊"
            return
        }

        try {
            mediaPlayer = MediaPlayer.create(this, R.raw.tutorial_voice)
            mediaPlayer?.setOnCompletionListener {
                it.release()
                mediaPlayer = null
                findViewById<Button>(R.id.btn_play_audio).text = "استمع للشرح الصوتي 🔊"
            }
            mediaPlayer?.start()
            findViewById<Button>(R.id.btn_play_audio).text = "إيقاف الشرح ⏸"
            Toast.makeText(this, "جاري تشغيل الشرح الصوتي... 🔊", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            Toast.makeText(this, "خطأ في تشغيل الصوت", Toast.LENGTH_SHORT).show()
        }
    }

    private fun dp(value: Int): Int {
        return (value * resources.displayMetrics.density).toInt()
    }

    override fun onDestroy() {
        super.onDestroy()
        mediaPlayer?.release()
        mediaPlayer = null
    }
}
