/*
 * 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.userpage

import android.text.format.DateFormat
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
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.defaultMinSize
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
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.draw.clip
import androidx.compose.ui.graphics.Color
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 androidx.compose.ui.unit.dp
import com.pico.spatial.ui.design.Button
import com.pico.spatial.ui.design.ButtonDefaults
import com.pico.spatial.ui.design.Checkbox
import com.pico.spatial.ui.design.CheckboxContentSize
import com.pico.spatial.ui.design.DatePicker
import com.pico.spatial.ui.design.HeaderStyle
import com.pico.spatial.ui.design.Icon
import com.pico.spatial.ui.design.LinearProgressDefaults
import com.pico.spatial.ui.design.LinearProgressIndicator
import com.pico.spatial.ui.design.Link
import com.pico.spatial.ui.design.PicoTheme
import com.pico.spatial.ui.design.Slider
import com.pico.spatial.ui.design.SliderDefaults
import com.pico.spatial.ui.design.Switch
import com.pico.spatial.ui.design.Text
import com.pico.spatial.ui.design.rememberDatePickerState
import com.pico.spatial.ui.design.windows.AlertDialog
import com.pico.spatial.ui.design.windows.Sheet
import com.pico.spatial.ui.foundation.hover.spatialHoverEffect
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 java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone

@Composable
fun SettingItemDefault(
    icon: Int,
    title: String,
    modifier: Modifier = Modifier,
    trailingContent: @Composable () -> Unit = {}
) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = modifier.padding(start = 16.dp, end = 4.dp).fillMaxWidth()
    ) {
        Icon(
            painter = painterResource(id = icon),
            contentDescription = null,
            modifier = Modifier.size(28.dp)
        )
        Spacer(Modifier.width(12.dp))
        Text(
            title,
            style = PicoTheme.typography.bodyLarge,
            color = Color.Vibrant.withVibrant(Vibrant.Darkest)
        )
        Spacer(Modifier.weight(1f))
        trailingContent()
    }
}

@Composable
fun SettingContentRow(height: Dp, modifier: Modifier = Modifier, content: @Composable () -> Unit) {
    Box(
        modifier
            .fillMaxWidth()
            .defaultMinSize(minHeight = height)
            .background(color = Color.Vibrant.withVibrant(Vibrant.Light)),
        contentAlignment = Alignment.Center
    ) {
        content()
    }
}

@Composable
fun DatePickerSheet(
    initialDateMillis: Long?,
    onDateSelected: (Long?) -> Unit,
    onDismissRequest: () -> Unit
) {
    val datePickerState =
        rememberDatePickerState(initialSelectedDateMillis = initialDateMillis ?: Date().time)
    Sheet(
        leadingAction = null,
        onDismissRequest = onDismissRequest,
        title = { Text(stringResource(R.string.sui_sample_date_picker_title)) },
        bottom = {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.End,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Button(
                    onClick = onDismissRequest,
                    colors =
                        ButtonDefaults.buttonColors(
                            containerColor = Color.Vibrant.withVibrant(Vibrant.Neutral),
                            contentColor = Color.Vibrant.withVibrant(Vibrant.Darkest)
                        ),
                ) {
                    Text(stringResource(R.string.sui_sample_cancel))
                }

                Spacer(modifier = Modifier.width(8.dp))

                Button(
                    onClick = {
                        onDateSelected(datePickerState.selectedDateMillis)
                        onDismissRequest()
                    }
                ) {
                    Text(stringResource(R.string.sui_sample_confirm))
                }
            }
        }
    ) {
        Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
            DatePicker(
                onDateSelected = {},
                headerStyle = HeaderStyle.Dropdown,
                state = datePickerState
            )
        }
    }
}

@Composable
fun UserProfile() {
    val defaultBirthdayStr = stringResource(R.string.sui_sample_default_birthday)
    val locale = Locale.getDefault()
    val dateFormat = remember(locale) {
        val pattern = DateFormat.getBestDateTimePattern(locale, "yyyyMMdd")
        SimpleDateFormat(pattern, locale).apply { timeZone = TimeZone.getTimeZone("UTC") }
    }
    val defaultBirthday = remember(locale, defaultBirthdayStr) {
        try {
            val date = SimpleDateFormat("yyyy-MM-dd", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }.parse(defaultBirthdayStr)
            date?.let { dateFormat.format(it) } ?: defaultBirthdayStr
        } catch (_: Exception) {
            defaultBirthdayStr
        }
    }
    var birthday by remember(defaultBirthday) { mutableStateOf(defaultBirthday) }
    var showDatePicker by remember { mutableStateOf(false) }
    Box {
        if (showDatePicker) {
            val initialMillis =
                remember(birthday) { runCatching { dateFormat.parse(birthday)?.time }.getOrNull() }

            DatePickerSheet(
                initialDateMillis = initialMillis,
                onDateSelected = { millis ->
                    millis?.let { birthday = dateFormat.format(Date(it)) }
                },
                onDismissRequest = { showDatePicker = false }
            )
        }

        Column(
            verticalArrangement = Arrangement.spacedBy(1.dp),
            modifier = Modifier.clip(RoundedCornerShape(8.dp))
        ) {
            SettingContentRow(72.dp) {
                SettingItemDefault(
                    icon = R.drawable.phone,
                    title = stringResource(R.string.sui_sample_phone_number_label)
                ) {
                    Text(
                        modifier = Modifier.padding(end = 12.dp),
                        text = stringResource(R.string.sui_sample_default_phone_number),
                        style = PicoTheme.typography.bodyLarge,
                        color = Color.Vibrant.withVibrant(Vibrant.Dark)
                    )
                }
            }

            SettingContentRow(
                72.dp,
                modifier = Modifier.spatialHoverEffect().clickable { showDatePicker = true }
            ) {
                SettingItemDefault(
                    icon = R.drawable.day,
                    title = stringResource(R.string.sui_sample_birthday_label)
                ) {
                    Row(
                        modifier = Modifier.padding(end = 12.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            birthday,
                            style = PicoTheme.typography.bodyLarge,
                            color = Color.Vibrant.withVibrant(Vibrant.Dark)
                        )
                        Spacer(modifier = Modifier.width(2.dp))
                        Icon(
                            modifier = Modifier.size(18.dp),
                            painter = painterResource(id = R.drawable.ic_arrow_right),
                            tint = Color.Vibrant.withVibrant(Vibrant.Dark),
                            contentDescription = null
                        )
                    }
                }
            }
        }
    }
}

@Composable
fun StorageContentRow() {
    val storageUsage by remember { mutableFloatStateOf(0.61f) }

    Box(modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))) {
        SettingContentRow(112.dp) {
            Column {
                Row(
                    modifier =
                        Modifier.fillMaxWidth().padding(vertical = 19.dp, horizontal = 16.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        painter = painterResource(R.drawable.cloud),
                        contentDescription = null,
                        modifier = Modifier.size(28.dp)
                    )

                    Column(
                        modifier = Modifier.fillMaxWidth().padding(start = 12.dp),
                        verticalArrangement = Arrangement.Center
                    ) {
                        Text(
                            text = stringResource(R.string.sui_sample_storage_space_label),
                            style = PicoTheme.typography.bodyLarge,
                            color = Color.Vibrant.withVibrant(Vibrant.Darkest)
                        )
                        Spacer(modifier = Modifier.height(4.dp))
                        Text(
                            text = stringResource(R.string.sui_sample_storage_usage_desc),
                            style = PicoTheme.typography.bodyMedium,
                            color = Color.Vibrant.withVibrant(Vibrant.Semidark)
                        )
                    }
                }
                Row(
                    modifier =
                        Modifier.fillMaxWidth().padding(start = 56.dp, end = 16.dp, bottom = 16.dp),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    LinearProgressIndicator(
                        modifier = Modifier.weight(1f),
                        progress = { storageUsage },
                        height = LinearProgressDefaults.Regular
                    )
                    Text(
                        text = "${(storageUsage * 100).toInt()}%",
                        style = PicoTheme.typography.bodySmall,
                        color = Color.Vibrant.withVibrant(Vibrant.UltraDark)
                    )
                }
            }
        }
    }
}

@Composable
fun BasicSettingContentRow() {
    Column(modifier = Modifier.fillMaxWidth()) {
        Text(
            stringResource(R.string.sui_sample_function_settings),
            style = PicoTheme.typography.titleMedium,
            modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),
            color = Color.Vibrant.withVibrant(Vibrant.Semidark)
        )

        StorageContentRow()
    }
}

@Composable
fun FontResizeContentRow(value: Float, onValueChange: (Float) -> Unit) {
    Column(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp)) {
        Row(verticalAlignment = Alignment.CenterVertically) {
            Icon(
                painter = painterResource(id = R.drawable.font),
                contentDescription = null,
                modifier = Modifier.size(28.dp)
            )

            Column(modifier = Modifier.padding(start = 12.dp)) {
                Text(
                    stringResource(R.string.sui_sample_font_size_label),
                    style = PicoTheme.typography.bodyLarge,
                    color = Color.Vibrant.withVibrant(Vibrant.Darkest)
                )
                Spacer(Modifier.height(4.dp))
                Text(
                    stringResource(R.string.sui_sample_font_size_desc),
                    style = PicoTheme.typography.bodyMedium,
                    color = Color.Vibrant.withVibrant(Vibrant.Semidark)
                )
            }
        }

        Spacer(Modifier.height(8.dp))

        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(4.dp)
        ) {
            Text(
                stringResource(R.string.sui_sample_font_size_small),
                style = PicoTheme.typography.bodySmall,
                color = Color.Vibrant.withVibrant(Vibrant.UltraDark)
            )
            Spacer(Modifier.width(4.dp))
            Slider(
                value = value,
                onValueChange = onValueChange,
                modifier = Modifier.weight(1f),
                sliderSpec = SliderDefaults.Small,
                colors =
                    SliderDefaults.sliderColors()
                        .copy(progressColor = Color.Vibrant.withVibrant(Vibrant.SemiLight)),
            )
            Spacer(Modifier.width(4.dp))
            Text(
                stringResource(R.string.sui_sample_font_size_large),
                style = PicoTheme.typography.bodySmall,
                color = Color.Vibrant.withVibrant(Vibrant.UltraDark)
            )
        }
    }
}

@Composable
fun JuvenileModeAlertDialog(onDismissRequest: () -> Unit, onConfirm: () -> Unit) {
    var checked by rememberSaveable { mutableStateOf(true) }
    Box {
        AlertDialog(
            onDismissRequest = onDismissRequest,
            title = {
                Text(
                    text = stringResource(R.string.sui_sample_juvenile_mode_title),
                    style = PicoTheme.typography.headlineLarge,
                    color = Color.Vibrant.withVibrant(Vibrant.Darkest)
                )
            },
            content = {
                Column {
                    Text(
                        text = stringResource(R.string.sui_sample_juvenile_mode_desc),
                        style = PicoTheme.typography.bodyMedium,
                        color = Color.Vibrant.withVibrant(Vibrant.UltraDark)
                    )

                    Spacer(Modifier.height(16.dp))
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Checkbox(
                            modifier = Modifier.size(32.dp),
                            checked = checked,
                            contentSize = CheckboxContentSize.Small,
                            onCheckedChange = { isChecked -> checked = isChecked }
                        )

                        Link(
                            onClick = {},
                        ) {
                            Text(stringResource(R.string.sui_sample_privacy_policy))
                        }
                    }
                }
            },
            buttons = {
                Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
                    Button(
                        onClick = onDismissRequest,
                        colors =
                            ButtonDefaults.buttonColors(
                                containerColor = Color.Vibrant.withVibrant(Vibrant.Neutral),
                                contentColor = Color.Vibrant.withVibrant(Vibrant.Darkest)
                            ),
                    ) {
                        Text(stringResource(R.string.sui_sample_cancel))
                    }
                    Spacer(Modifier.width(8.dp))
                    Button(
                        onClick = onConfirm,
                        enabled = checked,
                    ) {
                        Text(stringResource(R.string.sui_sample_confirm))
                    }
                }
            }
        )
    }
}

@Composable
fun OtherSettingContentStateless(
    isJuvenileMode: Boolean,
    onJuvenileModeChange: (Boolean) -> Unit,
    fontSizeScale: Float,
    onFontSizeChange: (Float) -> Unit,
    modifier: Modifier = Modifier
) {
    var showJuvenileDialog by remember { mutableStateOf(false) }

    Box {
        if (showJuvenileDialog) {
            JuvenileModeAlertDialog(
                onDismissRequest = {
                    showJuvenileDialog = false
                    onJuvenileModeChange(false)
                },
                onConfirm = { showJuvenileDialog = false }
            )
        }
        Column(
            verticalArrangement = Arrangement.spacedBy(1.dp),
            modifier = modifier.clip(RoundedCornerShape(8.dp))
        ) {
            SettingContentRow(72.dp) {
                SettingItemDefault(
                    icon = R.drawable.youth,
                    title = stringResource(R.string.sui_sample_juvenile_mode_label)
                ) {
                    Switch(
                        checked = isJuvenileMode,
                        onCheckedChange = { checked ->
                            onJuvenileModeChange(checked)
                            if (checked) {
                                showJuvenileDialog = true
                            }
                        }
                    )
                }
            }

            SettingContentRow(128.dp) {
                FontResizeContentRow(value = fontSizeScale, onValueChange = onFontSizeChange)
            }
        }
    }
}

@Composable
fun OtherSettingContentStateful() {
    var isJuvenileMode by remember { mutableStateOf(false) }
    var fontSizeScale by remember { mutableFloatStateOf(0.34f) }

    OtherSettingContentStateless(
        isJuvenileMode = isJuvenileMode,
        onJuvenileModeChange = { isJuvenileMode = it },
        fontSizeScale = fontSizeScale,
        onFontSizeChange = { fontSizeScale = it }
    )
}

@Composable
fun SettingContent() {
    Column(modifier = Modifier.fillMaxSize().padding(start = 168.dp, end = 168.dp)) {
        UserProfile()
        Spacer(Modifier.height(16.dp))

        BasicSettingContentRow()
        Spacer(Modifier.height(12.dp))

        OtherSettingContentStateful()
    }
}

@Preview(showBackground = true, widthDp = 1280, heightDp = 720)
@Composable
fun SettingContentPreview() {
    PicoTheme { SettingContent() }
}
