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

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 issueTypes = listOf("Ballistics", "Printing", "Sensors", "Other")

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SupportScreen(onBack: () -> Unit) {
    val context = LocalContext.current
    var selectedIssueType by remember { mutableStateOf(issueTypes[0]) }
    var descriptionText   by remember { mutableStateOf("") }
    var stepsText         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("Contact Support", 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),
        ) {
            // ── Issue type ────────────────────────────────────────────────────
            InstrumentPanel(label = "Issue Type") {
                Row(
                    modifier              = Modifier.padding(top = 4.dp),
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                ) {
                    issueTypes.forEach { type ->
                        val selected = selectedIssueType == type
                        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 { selectedIssueType = type }
                                .padding(horizontal = 16.dp, vertical = 10.dp),
                            contentAlignment = Alignment.Center,
                        ) {
                            Text(
                                text  = type,
                                style = BadgeStyle.copy(fontSize = 14.sp),
                                color = if (selected) Color.Black else ColorTextMuted,
                            )
                        }
                    }
                }
            }

            // ── Describe issue ─────────────────────────────────────────────────
            InstrumentPanel(label = "Describe Your Issue") {
                OutlinedTextField(
                    value         = descriptionText,
                    onValueChange = { descriptionText = it },
                    placeholder   = { Text("What happened? What were you expecting?", style = BodyStyle, color = ColorTextMuted) },
                    modifier      = Modifier.fillMaxWidth().heightIn(min = 140.dp),
                    minLines      = 5,
                    colors        = OutlinedTextFieldDefaults.colors(
                        focusedBorderColor      = ColorAmber,
                        unfocusedBorderColor    = ColorBorder,
                        focusedContainerColor   = ColorBackground,
                        unfocusedContainerColor = ColorBackground,
                        focusedTextColor        = ColorTextPrimary,
                        unfocusedTextColor      = ColorTextPrimary,
                        cursorColor             = ColorAmber,
                    ),
                    textStyle = BodyStyle,
                )
            }

            // ── Steps to reproduce ────────────────────────────────────────────
            InstrumentPanel(label = "Steps to Reproduce") {
                OutlinedTextField(
                    value         = stepsText,
                    onValueChange = { stepsText = it },
                    placeholder   = { Text("1. Open the app…", style = BodyStyle, color = ColorTextMuted) },
                    modifier      = Modifier.fillMaxWidth().heightIn(min = 100.dp),
                    minLines      = 4,
                    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)
            }

            // ── Send button ───────────────────────────────────────────────────
            ActionButton(
                text     = "Send to Support",
                enabled  = descriptionText.isNotBlank(),
                modifier = Modifier.fillMaxWidth(),
                onClick  = {
                    val body = buildString {
                        appendLine("Issue Type: $selectedIssueType")
                        appendLine()
                        appendLine("Description:")
                        appendLine(descriptionText.trim())
                        if (stepsText.isNotBlank()) {
                            appendLine()
                            appendLine("Steps to Reproduce:")
                            appendLine(stepsText.trim())
                        }
                        appendLine()
                        appendLine("---")
                        append(deviceInfo)
                    }
                    val intent = Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:support@scope-dope.com")).apply {
                        putExtra(Intent.EXTRA_SUBJECT, "ScopeDOPE Support: $selectedIssueType")
                        putExtra(Intent.EXTRA_TEXT, body)
                    }
                    context.startActivity(Intent.createChooser(intent, null))
                },
            )

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

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