package com.jordanbot.autoride.service

import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Build
import android.os.IBinder
import android.view.Gravity
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.EditText
import android.widget.Switch
import android.widget.TextView
import com.jordanbot.autoride.R

class OverlayService : Service() {

    private lateinit var windowManager: WindowManager
    private lateinit var floatingView: View
    private lateinit var expandedView: View
    private lateinit var params: WindowManager.LayoutParams

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onCreate() {
        super.onCreate()
        
        windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        
        floatingView = inflater.inflate(R.layout.overlay_floating, null)
        expandedView = inflater.inflate(R.layout.overlay_expanded, null)

        val layoutFlag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        } else {
            WindowManager.LayoutParams.TYPE_PHONE
        }

        params = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            layoutFlag,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT
        )
        
        params.gravity = Gravity.TOP or Gravity.START
        params.x = 0
        params.y = 100

        windowManager.addView(floatingView, params)
        
        setupFloatingView()
        setupExpandedView()
    }

    private fun setupFloatingView() {
        val tvBubble = floatingView.findViewById<TextView>(R.id.tv_bubble)
        
        floatingView.setOnTouchListener(object : View.OnTouchListener {
            private var initialX: Int = 0
            private var initialY: Int = 0
            private var initialTouchX: Float = 0f
            private var initialTouchY: Float = 0f
            private var isClick = false

            override fun onTouch(v: View, event: MotionEvent): Boolean {
                when (event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        initialX = params.x
                        initialY = params.y
                        initialTouchX = event.rawX
                        initialTouchY = event.rawY
                        isClick = true
                        return true
                    }
                    MotionEvent.ACTION_MOVE -> {
                        val diffX = (event.rawX - initialTouchX).toInt()
                        val diffY = (event.rawY - initialTouchY).toInt()
                        
                        if (Math.abs(diffX) > 10 || Math.abs(diffY) > 10) {
                            isClick = false
                        }
                        
                        params.x = initialX + diffX
                        params.y = initialY + diffY
                        windowManager.updateViewLayout(floatingView, params)
                        return true
                    }
                    MotionEvent.ACTION_UP -> {
                        if (isClick) {
                            showExpandedView()
                        }
                        return true
                    }
                }
                return false
            }
        })
    }

    private fun setupExpandedView() {
        val btnClose = expandedView.findViewById<Button>(R.id.btn_save_close)
        val etMinPrice = expandedView.findViewById<EditText>(R.id.et_min_price)
        val switchStatus = expandedView.findViewById<Switch>(R.id.switch_bot_status)

        btnClose.setOnClickListener {
            // TODO: Save to SharedPreferences/FilterEngine
            val minPriceStr = etMinPrice.text.toString()
            val isEnabled = switchStatus.isChecked
            
            // Update bubble UI
            val tvBubble = floatingView.findViewById<TextView>(R.id.tv_bubble)
            if (isEnabled) {
                tvBubble.text = "Bot\nON"
                tvBubble.setBackgroundResource(R.drawable.bg_bubble)
            } else {
                tvBubble.text = "Bot\nOFF"
                // Would need a red bubble background here in a real app
            }
            
            hideExpandedView()
        }
    }

    private fun showExpandedView() {
        windowManager.removeView(floatingView)
        
        // Change params to focusable so user can type in EditText
        val expandedParams = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY else WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
            PixelFormat.TRANSLUCENT
        )
        expandedParams.gravity = Gravity.CENTER
        
        windowManager.addView(expandedView, expandedParams)
    }

    private fun hideExpandedView() {
        windowManager.removeView(expandedView)
        
        // Reset params to non-focusable
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
        windowManager.addView(floatingView, params)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (::floatingView.isInitialized) windowManager.removeView(floatingView)
        if (::expandedView.isInitialized && expandedView.parent != null) windowManager.removeView(expandedView)
    }
}
