// Copyright (C) 2026 Jason M. Schwefel. All Rights Reserved.
package com.coldboreballisticsllc.scopedope.ui.screens.feedback

import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.coldboreballisticsllc.scopedope.BuildConfig
import com.coldboreballisticsllc.scopedope.ui.components.ActionButton
import com.coldboreballisticsllc.scopedope.ui.components.InstrumentPanel
import com.coldboreballisticsllc.scopedope.ui.components.NotchedCornerShape
import com.coldboreballisticsllc.scopedope.ui.theme.*

private val categories = listOf("Bug Report", "Feature Request", "General")

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FeedbackScreen(onBack: () -> Unit) {
    val context = LocalContext.current
    var selectedCategory by remember { mutableStateOf(categories[0]) }
    var feedbackText     by remember { mutableStateOf("") }

    val deviceInfo = buildString {
        appendLine("ScopeDOPE v${BuildConfig.VERSION_NAME}")
        appendLine("Android ${Build.VERSION.RELEASE} · API ${Build.VERSION.SDK_INT}")
        append(Build.MODEL)
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Send Feedback", style = MaterialTheme.typography.titleLarge) },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor    = ColorBackground,
                    titleContentColor = ColorTextPrimary,
                ),
            )
        },
        containerColor = ColorBackground,
    ) { padding ->
        Column(
            modifier = Modifier
                .padding(padding)
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .padding(horizontal = 14.dp, vertical = 14.dp),
            verticalArrangement = Arrangement.spacedBy(14.dp),
        ) {
            // ── Category ──────────────────────────────────────────────────────
            InstrumentPanel(label = "Category") {
                Row(
                    modifier              = Modifier.padding(top = 4.dp),
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                ) {
                    categories.forEach { cat ->
                        val selected = selectedCategory == cat
                        val shape    = NotchedCornerShape(6.dp)
                        Box(
                            modifier = Modifier
                                .clip(shape)
                                .background(if (selected) ColorAmber else ColorSurface2)
                                .border(1.dp, if (selected) ColorAmber else ColorBorder, shape)
                                .clickable { selectedCategory = cat }
                                .padding(horizontal = 16.dp, vertical = 10.dp),
                            contentAlignment = Alignment.Center,
                        ) {
                            Text(
                                text  = cat,
                                style = BadgeStyle.copy(fontSize = 14.sp),
                                color = if (selected) Color.Black else ColorTextMuted,
                            )
                        }
                    }
                }
            }

            // ── Feedback text ─────────────────────────────────────────────────
            InstrumentPanel(label = "Your Feedback") {
                OutlinedTextField(
                    value         = feedbackText,
                    onValueChange = { feedbackText = it },
                    placeholder   = { Text("Describe the issue or your idea…", style = BodyStyle, color = ColorTextMuted) },
                    modifier      = Modifier.fillMaxWidth().heightIn(min = 160.dp),
                    minLines      = 6,
                    colors        = OutlinedTextFieldDefaults.colors(
                        focusedBorderColor      = ColorAmber,
                        unfocusedBorderColor    = ColorBorder,
                        focusedContainerColor   = ColorBackground,
                        unfocusedContainerColor = ColorBackground,
                        focusedTextColor        = ColorTextPrimary,
                        unfocusedTextColor      = ColorTextPrimary,
                        cursorColor             = ColorAmber,
                    ),
                    textStyle = BodyStyle,
                )
            }

            // ── Device info ───────────────────────────────────────────────────
            InstrumentPanel(label = "Device Info") {
                Text(deviceInfo, style = FieldLabelStyle.copy(lineHeight = 22.sp), color = ColorTextMuted)
                Spacer(Modifier.height(8.dp))
                Text(
                    "Included automatically to help us diagnose issues.",
                    style = BodySubStyle,
                    color = ColorTextMuted,
                )
            }

            // ── Send button ───────────────────────────────────────────────────
            ActionButton(
                text     = "Send Feedback",
                enabled  = feedbackText.isNotBlank(),
                modifier = Modifier.fillMaxWidth(),
                onClick  = {
                    val body = buildString {
                        appendLine("Category: $selectedCategory")
                        appendLine()
                        appendLine(feedbackText.trim())
                        appendLine()
                        appendLine("---")
                        append(deviceInfo)
                    }
                    val intent = Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:feedback@scope-dope.com")).apply {
                        putExtra(Intent.EXTRA_SUBJECT, "ScopeDOPE Feedback: $selectedCategory")
                        putExtra(Intent.EXTRA_TEXT, body)
                    }
                    context.startActivity(Intent.createChooser(intent, null))
                },
            )

            Text(
                text  = "Sends to feedback@scope-dope.com",
                style = BodySubStyle,
                color = ColorAmberDim,
                modifier = Modifier.fillMaxWidth().wrapContentWidth(Alignment.CenterHorizontally),
            )

            Spacer(Modifier.height(24.dp))
        }
    }
}
