@file:Suppress("AssignedValueIsNeverRead")

package eu.gaudian.translator.view.composable

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.union
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.BottomSheetDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.ProvideTextStyle
import androidx.compose.material3.SheetValue
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.DialogProperties
import eu.gaudian.translator.R
import eu.gaudian.translator.view.hints.Hint
import eu.gaudian.translator.view.hints.HintBottomSheet
import eu.gaudian.translator.view.hints.LocalShowHints

@Composable
fun AppDialog(
    onDismissRequest: () -> Unit,
    title: (@Composable () -> Unit)? = null,
    hintContent: Hint? = null,
    content: @Composable () -> Unit
) {
    // 1. Swipe Resistance: Prevent accidental dismissal
    val sheetState = rememberModalBottomSheetState(
        skipPartiallyExpanded = true,
        confirmValueChange = { newState ->
            // Return false to block the sheet from hiding via swipe
            newState != SheetValue.Hidden
        }
    )
    var showBottomSheet by remember { mutableStateOf(false) }

    ModalBottomSheet(
        onDismissRequest = onDismissRequest,
        sheetState = sheetState,
        // 2. Keyboard Handling (Material3 1.4.0+): Respect IME insets
        contentWindowInsets = { BottomSheetDefaults.windowInsets.union(WindowInsets.ime) }
    ) {
        Column(
            modifier = Modifier
                .padding(horizontal = 24.dp)
                .padding(bottom = 24.dp)
            // Note: Vertical scroll is applied to the inner content column below
        ) {
            // 3. Header with Title, Hint Icon, and Close (X) Icon
            DialogHeader(
                title = title,
                hintContent = hintContent,
                onHintClick = { showBottomSheet = true },
                onCloseClick = onDismissRequest
            )

            Spacer(modifier = Modifier.height(16.dp))

            // 4. Scrollable Content Area
            Column(
                modifier = Modifier
                    .verticalScroll(rememberScrollState())
            ) {
                content()
                // Extra spacer at bottom so last field isn't glued to keyboard
                Spacer(modifier = Modifier.height(16.dp))
            }
        }
    }

    if (showBottomSheet) {
        EnhancedHintBottomSheet(
            onDismissRequest = { showBottomSheet = false },
            content = {hintContent?.Render()},
            parentTitle = title
        )
    }
}

@Composable
fun AppAlertDialog(
    onDismissRequest: () -> Unit,
    confirmButton: @Composable () -> Unit,
    modifier: Modifier = Modifier,
    dismissButton: @Composable (() -> Unit)? = null,
    icon: @Composable (() -> Unit)? = null,
    title: @Composable (() -> Unit)? = null,
    text: @Composable (() -> Unit)? = null,
    properties: DialogProperties = DialogProperties(),
    hintContent:Hint? = null,
) {
    val sheetState = rememberModalBottomSheetState()
    var showBottomSheet by remember { mutableStateOf(false) }

    AlertDialog(
        onDismissRequest = onDismissRequest,
        confirmButton = confirmButton,
        modifier = modifier,
        dismissButton = dismissButton,
        icon = icon,
        title = title?.let {
            {
                // Reusing a simplified title row for standard AlertDialogs
                // (AlertDialogs don't need the close 'X' as much as BottomSheets do)
                DialogTitleWithHint(
                    title = it,
                    hintContent = hintContent,
                    onHintClick = { showBottomSheet = true }
                )
            }
        },
        text = text,
        properties = properties
    )

    if (showBottomSheet) {
        hintContent?.let {
            HintBottomSheet(
                onDismissRequest = { showBottomSheet = false },
                sheetState = sheetState,
                content = it
            )
        }
    }
}

/**
 * Standard Dialog Header for BottomSheets.
 * Includes Title (Left), Hint Icon (Right), and Close 'X' Button (Far Right).
 */
@Composable
private fun DialogHeader(
    title: (@Composable () -> Unit)?,
    hintContent: Hint? = null,
    onHintClick: () -> Unit,
    onCloseClick: () -> Unit
) {
    val showHints = LocalShowHints.current

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(top = 8.dp), // Slight top padding
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        // Left side: Title
        Box(modifier = Modifier.weight(1f)) {
            if (title != null) {
                ProvideTextStyle(value = MaterialTheme.typography.headlineSmall) {
                    title()
                }
            }
        }

        // Right side: Icons (Hint + Close)
        Row(
            verticalAlignment = Alignment.CenterVertically
        ) {
            // Hint Icon
            if (showHints && hintContent != null) {
                IconButton(onClick = onHintClick) {
                    Icon(
                        imageVector = AppIcons.Help,
                        contentDescription = stringResource(R.string.show_hint),
                        tint = MaterialTheme.colorScheme.secondary
                    )
                }
            }

            IconButton(onClick = onCloseClick) {
                Icon(
                    imageVector = AppIcons.Close,
                    contentDescription = stringResource(R.string.label_close),
                    tint = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.size(28.dp)
                )
            }
        }
    }
}

/**
 * Simplified Title Row for standard AlertDialogs (no Close 'X').
 */
@Composable
private fun DialogTitleWithHint(
    title: @Composable () -> Unit,
    hintContent: Hint? = null,
    onHintClick: () -> Unit
) {
    val showHints = LocalShowHints.current
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Box(modifier = Modifier.weight(1f)) {
            ProvideTextStyle(value = MaterialTheme.typography.headlineSmall) {
                title()
            }
        }
        if (showHints && hintContent != null) {
            IconButton(onClick = onHintClick) {
                Icon(
                    imageVector = AppIcons.Help,
                    contentDescription = stringResource(R.string.show_hint),
                    tint = MaterialTheme.colorScheme.secondary
                )
            }
        }
    }
}

@Composable
private fun EnhancedHintBottomSheet(
    onDismissRequest: () -> Unit,
    content: @Composable (() -> Unit)?,
    parentTitle: (@Composable () -> Unit)?,
    sheetGesturesEnabled : Boolean = false
) {

    rememberCoroutineScope()

    val sheetState = rememberModalBottomSheetState(
        skipPartiallyExpanded = true
    )

    ModalBottomSheet(
        onDismissRequest = onDismissRequest,
        sheetState = sheetState,
        sheetGesturesEnabled = sheetGesturesEnabled,
        contentWindowInsets = { BottomSheetDefaults.windowInsets.union(WindowInsets.ime) }
    ) {
        Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
            // Header with back navigation context
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                IconButton(onClick = onDismissRequest) {
                    Icon(
                        imageVector = AppIcons.ArrowBack,
                        contentDescription = stringResource(R.string.cd_back),
                        tint = MaterialTheme.colorScheme.primary
                    )
                }
                Spacer(modifier = Modifier.width(8.dp))
                Text(
                    text = stringResource(R.string.text_hint),
                    style = MaterialTheme.typography.titleMedium,
                    color = MaterialTheme.colorScheme.primary
                )
                parentTitle?.let {
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = "•",
                        style = MaterialTheme.typography.titleMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Box(modifier = Modifier.weight(1f)) {
                        ProvideTextStyle(value = MaterialTheme.typography.bodyMedium) {
                            it()
                        }
                    }
                }
            }

            Spacer(modifier = Modifier.height(16.dp))

            // Scrollable content area
            Column(
                modifier = Modifier
                    .weight(1f, fill = false)
                    .verticalScroll(rememberScrollState())
            ) {
                content?.invoke()
            }

            Spacer(modifier = Modifier.height(16.dp))

            // Enhanced action button
            AppButton(
                onClick = {
                    onDismissRequest()
                },
                modifier = Modifier
                    .align(Alignment.End)
                    .padding(bottom = 8.dp)
            ) {
                Text(stringResource(R.string.got_it))
            }
        }
    }
}

@Suppress("HardCodedStringLiteral")
@Preview
@Composable
fun AppDialogPreview() {
    AppDialog(
        onDismissRequest = {},
        title = { Text("Dialog Title") },
        content = {
            Column {
                Text("Content line 1")
                Spacer(Modifier.height(8.dp))
                Text("Content line 2")
            }
        }
    )
}

@Suppress("HardCodedStringLiteral")
@Preview
@Composable
fun AppDialogNoTitlePreview() {
    AppDialog(
        onDismissRequest = {},
        content = {
            Column {
                Text("Dialog without title")
                Spacer(Modifier.height(8.dp))
                Text("Just content here")
            }
        }
    )
}

@Suppress("HardCodedStringLiteral")
@Preview
@Composable
fun AppDialogNoHintPreview() {
    AppDialog(
        onDismissRequest = {},
        title = { Text("Dialog Without Hint") },
        content = {
            Column {
                Text("This dialog has no hint functionality")
                Spacer(Modifier.height(8.dp))
                Text("Only title and content")
            }
        }
    )
}

@Suppress("HardCodedStringLiteral")
@Preview
@Composable
fun AppDialogLongContentPreview() {
    AppDialog(
        onDismissRequest = {},
        title = { Text("Long Content Dialog") },
        content = {
            Column {
                Text("This is a long content dialog to test scrolling")
                Spacer(Modifier.height(8.dp))
                Text("Line 2 of content")
                Spacer(Modifier.height(8.dp))
                Text("Line 3 of content")
                Spacer(Modifier.height(8.dp))
                Text("Line 4 of content")
                Spacer(Modifier.height(8.dp))
                Text("Line 5 of content")
                Spacer(Modifier.height(8.dp))
                Text("Line 6 of content")
                Spacer(Modifier.height(8.dp))
                Text("Line 7 of content")
                Spacer(Modifier.height(8.dp))
                Text("Line 8 - This should trigger scrolling")
            }
        }
    )
}

@Suppress("HardCodedStringLiteral")
@Preview
@Composable
fun AppAlertDialogPreview() {
    AppAlertDialog(
        onDismissRequest = {},
        confirmButton = {
            TextButton(onClick = {}) {
                Text("Confirm")
            }
        },
        dismissButton = {
            TextButton(onClick = {}) {
                Text("Dismiss")
            }
        },
        icon = {
            Icon(
                imageVector = AppIcons.Help,
                contentDescription = null
            )
        },
        title = { Text("Alert Dialog Title") },
        text = { Text("This is the alert dialog text.") },
    )
}

@Suppress("HardCodedStringLiteral")
@Preview
@Composable
fun AppAlertDialogNoIconPreview() {
    AppAlertDialog(
        onDismissRequest = {},
        confirmButton = {
            TextButton(onClick = {}) {
                Text("OK")
            }
        },
        title = { Text("Simple Alert") },
        text = { Text("This alert has no icon but has a title and text.") }
    )
}

@Suppress("HardCodedStringLiteral")
@Preview
@Composable
fun AppAlertDialogOnlyConfirmPreview() {
    AppAlertDialog(
        onDismissRequest = {},
        confirmButton = {
            TextButton(onClick = {}) {
                Text("Got it")
            }
        },
        icon = {
            Icon(
                imageVector = AppIcons.Help,
                contentDescription = null
            )
        },
        title = { Text("Confirmation Required") },
        text = { Text("This dialog only has a confirm button.") }
    )
}

@Suppress("HardCodedStringLiteral")
@Preview
@Composable
fun AppAlertDialogLongTextPreview() {
    AppAlertDialog(
        onDismissRequest = {},
        confirmButton = {
            TextButton(onClick = {}) {
                Text("I Understand")
            }
        },
        dismissButton = {
            TextButton(onClick = {}) {
                Text("Cancel")
            }
        },
        title = { Text("Terms and Conditions") },
        text = {
            Column {
                Text("This is a long text dialog to test how the alert dialog handles extended content.")
                Spacer(Modifier.height(8.dp))
                Text("Second paragraph of the terms and conditions that explains important details.")
                Spacer(Modifier.height(8.dp))
                Text("Third paragraph with additional information that users need to be aware of.")
            }
        },
    )
}

@Suppress("HardCodedStringLiteral")
@Preview
@Composable
fun AppAlertDialogMinimalPreview() {
    AppAlertDialog(
        onDismissRequest = {},
        confirmButton = {
            TextButton(onClick = {}) {
                Text("OK")
            }
        },
        text = { Text("Minimal dialog with only text and confirm button.") }
    )
}