/*
 * Copyright 2025 - 2026 PICO. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.pico.spatialui.sample.pages

import android.annotation.SuppressLint
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.pico.spatial.ui.design.ButtonDefaults
import com.pico.spatial.ui.design.CircularProgressIndicator
import com.pico.spatial.ui.design.Divider
import com.pico.spatial.ui.design.Icon
import com.pico.spatial.ui.design.IconButton
import com.pico.spatial.ui.design.NumberField
import com.pico.spatial.ui.design.PicoTheme
import com.pico.spatial.ui.design.Text
import com.pico.spatial.ui.design.TitleBar
import com.pico.spatial.ui.design.menu.Menu
import com.pico.spatial.ui.design.menu.MenuItem
import com.pico.spatial.ui.design.menu.rememberMenuPositionProvider
import com.pico.spatial.ui.design.windows.CoachmarkBox
import com.pico.spatial.ui.design.windows.CoachmarkDefaults
import com.pico.spatial.ui.design.windows.CoachmarkDirection
import com.pico.spatial.ui.design.windows.LocalSnackbarHostState
import com.pico.spatial.ui.design.windows.RichCoachmark
import com.pico.spatial.ui.design.windows.SnackbarHost
import com.pico.spatial.ui.design.windows.SpatialPopup
import com.pico.spatial.ui.design.windows.Toolbar
import com.pico.spatial.ui.design.windows.popup.HorizontalPlacement
import com.pico.spatial.ui.design.windows.popup.VerticalPlacement
import com.pico.spatial.ui.design.windows.rememberSpatialPopupPositionProvider
import com.pico.spatial.ui.foundation.tooltip
import com.pico.spatial.ui.foundation.vibrant.Vibrant
import com.pico.spatial.ui.foundation.vibrant.withVibrant
import com.pico.spatial.ui.graphics.Vibrant
import com.pico.spatialui.sample.R
import com.pico.spatialui.sample.viewmodel.CoachMarkManager
import kotlinx.coroutines.launch

@SuppressLint("RestrictedApi")
@Suppress("UNUSED_PARAMETER")
@Composable
fun ContentDetailPage(itemId: String, onBack: () -> Unit) {
    SnackbarHost {
        Box(modifier = Modifier.fillMaxSize()) {
            AsyncImage(
                model = R.drawable.img_detail_bg,
                contentDescription = null,
                modifier = Modifier.fillMaxSize(),
                contentScale = ContentScale.Crop
            )

            TitleBar(
                title = {
                    IconButton(
                        onClick = onBack,
                        modifier = Modifier.size(48.dp),
                        colors =
                            ButtonDefaults.buttonColors(
                                contentColor = PicoTheme.colorTokens.LabelPrimaryLight,
                                containerColor = Color.Vibrant.withVibrant(Vibrant.Neutral)
                            ),
                    ) {
                        Icon(
                            painter = painterResource(R.drawable.back),
                            contentDescription = null,
                            modifier = Modifier.size(20.dp)
                        )
                    }
                }
            )
        }

        val snackState = LocalSnackbarHostState.current
        val scope = rememberCoroutineScope()

        /**
         * Toolbar is a Window(a horizontal bar like the bottom navigation bar), which is at the
         * bottom of the current window.
         */
        Toolbar(cornerSize = 37.dp) {
            ToolbarContentWithCoachMark(itemId) {
                ToolbarItem(R.drawable.left, enabled = false) {}
                ToolbarItem(R.drawable.right, enabled = false) {}

                ToolbarItemDivider()

                ToolbarItem(R.drawable.rotate, enabled = false) {}

                ToolbarItem(R.drawable.zoom_out, enabled = false) {}

                ToolbarItemWithPopupView(R.drawable.zoom_in) {
                    var value by rememberSaveable { mutableIntStateOf(100) }
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.size(width = 260.dp, height = 64.dp)
                    ) {
                        Spacer(modifier = Modifier.size(16.dp))
                        Text(
                            stringResource(R.string.sui_sample_content_detail_page_zoom_ratio),
                            style = PicoTheme.typography.bodyLarge,
                            modifier = Modifier.weight(1f)
                        )
                        NumberField(value, onValueChange = { value = it }, editable = false)
                        Spacer(modifier = Modifier.size(16.dp))
                    }
                }

                ToolbarItemDivider()

                val message = stringResource(R.string.sui_sample_content_detail_page_snack_message)
                ToolbarItem(
                    R.drawable.cube,
                    modifier =
                        Modifier.tooltip(
                            text =
                                stringResource(R.string.sui_sample_content_detail_page_3d_convert)
                        )
                ) {
                    scope.launch {
                        snackState.show(
                            message = message,
                            leadingIcon = { CircularProgressIndicator() }
                        )
                    }
                }

                ToolbarItemWithMenu(R.drawable.more) {
                    MenuItem(
                        title = {
                            Text(
                                text = stringResource(R.string.sui_sample_content_detail_page_share)
                            )
                        },
                        onClick = {},
                        leadingIcon = {
                            Icon(
                                painter = painterResource(R.drawable.share),
                                contentDescription = null
                            )
                        }
                    )

                    Spacer(modifier = Modifier.height(8.dp))
                    Divider(modifier = Modifier.height(1.dp), color = Color(0x8080803D))
                    Spacer(modifier = Modifier.height(8.dp))

                    MenuItem(
                        title = {
                            Text(
                                text =
                                    stringResource(R.string.sui_sample_content_detail_page_report)
                            )
                        },
                        onClick = {},
                        leadingIcon = {
                            Icon(
                                painter = painterResource(R.drawable.alarm),
                                contentDescription = null
                            )
                        }
                    )

                    MenuItem(
                        title = {
                            Text(
                                text =
                                    stringResource(
                                        R.string.sui_sample_content_detail_page_immersive_experience
                                    )
                            )
                        },
                        onClick = {},
                        leadingIcon = {
                            Icon(
                                painter = painterResource(R.drawable.ic_immersive),
                                contentDescription = null
                            )
                        }
                    )
                }
            }
        }
    }
}

@Composable
fun ToolbarContentWithCoachMark(id: String, content: @Composable () -> Unit) {
    var showCoachMark by rememberSaveable { mutableStateOf(!CoachMarkManager.isCoachMarkShown(id)) }

    CoachmarkBox(
        showCoachmark = showCoachMark,
        direction = CoachmarkDirection.Above,
        modifier = Modifier,
        coachmark = {
            RichCoachmark(
                title = {
                    Text(
                        text =
                            stringResource(
                                R.string.sui_sample_content_detail_page_mark_interactive_function
                            )
                    )
                },
                content = {
                    Text(
                        text =
                            stringResource(R.string.sui_sample_content_detail_page_mark_description)
                    )
                },
                image = {
                    Image(
                        painter = painterResource(R.drawable.img_coachmark_toolbar),
                        contentDescription = null
                    )
                },
                buttons = {
                    CoachmarkDefaults.CoachmarkButton(
                        onClick = {
                            showCoachMark = false
                            CoachMarkManager.setCoachMarkShown(id)
                        }
                    ) {
                        Text(
                            text = stringResource(R.string.sui_sample_i_known),
                            style = PicoTheme.typography.labelMedium
                        )
                    }
                }
            )
        }
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            content()
        }
    }
}

@Composable
fun ToolbarItemDivider() {
    Icon(
        painter = painterResource(R.drawable.divider),
        contentDescription = null,
        modifier = Modifier.size(width = 8.dp, height = 40.dp),
        tint = Color.Unspecified
    )
}

@Composable
fun ToolbarItem(
    @DrawableRes iconRes: Int,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    onClick: () -> Unit
) {
    IconButton(
        onClick = onClick,
        modifier = modifier.size(48.dp),
        colors =
            ButtonDefaults.buttonColors(
                contentColor = Color.Vibrant.withVibrant(Vibrant.Darkest),
                containerColor = Color.Transparent
            ),
        enabled = enabled
    ) {
        Icon(
            painter = painterResource(iconRes),
            contentDescription = null,
            modifier = Modifier.size(20.dp)
        )
    }
}

@Composable
fun ToolbarItemWithPopupView(@DrawableRes iconRes: Int, popupContent: @Composable () -> Unit) {
    var showPopup by rememberSaveable { mutableStateOf(false) }

    Box {
        ToolbarItem(
            iconRes,
            modifier =
                Modifier.tooltip(
                    text = stringResource(R.string.sui_sample_content_detail_page_zoom_out)
                )
        ) {
            showPopup = !showPopup
        }

        if (showPopup) {
            SpatialPopup(
                onDismissRequest = { showPopup = false },
                defaultMinHeight = 64.dp,
                defaultMinWidth = 128.dp,
                popupPositionProvider =
                    rememberSpatialPopupPositionProvider(
                        verticalPlacement = VerticalPlacement.above(offset = (-24).dp)
                    )
            ) {
                popupContent()
            }
        }
    }
}

@Composable
fun ToolbarItemWithMenu(@DrawableRes iconRes: Int, content: @Composable (ColumnScope.() -> Unit)) {
    var showMenu by rememberSaveable { mutableStateOf(false) }

    Box {
        ToolbarItem(
            iconRes,
            modifier =
                Modifier.tooltip(
                    text = stringResource(R.string.sui_sample_content_detail_page_more_actions)
                )
        ) {
            showMenu = !showMenu
        }

        if (showMenu) {
            Menu(
                positionProvider =
                    rememberMenuPositionProvider(
                        horizontalPlacement = HorizontalPlacement.alignStart(),
                        verticalPlacement = VerticalPlacement.above(offset = (-24).dp)
                    ),
                onDismissRequest = { showMenu = false }
            ) {
                content()
            }
        }
    }
}

@Preview(showBackground = false, widthDp = 1280, heightDp = 720)
@Composable
fun ContentDetailPagePreview() {
    PicoTheme { ContentDetailPage(itemId = "itemId_4391") {} }
}
