package com.pixelized.headache.ui.page.home

import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.background
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.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.CalendarToday
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.outlined.Info
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.pixelized.headache.R
import com.pixelized.headache.ui.common.toolbar.Toolbar
import com.pixelized.headache.ui.navigation.destination.MonthSummaryDestination
import com.pixelized.headache.ui.navigation.destination.ReportDestination
import com.pixelized.headache.ui.navigation.destination.YearSummaryDestination
import com.pixelized.headache.ui.navigation.destination.navigateToMonthSummary
import com.pixelized.headache.ui.navigation.destination.navigateToReport
import com.pixelized.headache.ui.navigation.destination.navigateToYearSummary
import com.pixelized.headache.ui.navigation.home.HomeNavDisplay
import com.pixelized.headache.ui.navigation.home.HomeNavigator
import com.pixelized.headache.ui.page.event.edit.EventEditBottomSheet
import com.pixelized.headache.ui.page.event.edit.EventEditBottomSheetViewModel
import com.pixelized.headache.ui.theme.color.HeadacheColorPalette
import com.pixelized.headache.utils.extention.capitalize
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale

@Stable
data class BottomBarItemUio(
    val selectedIcon: Int,
    val unselectedIcon: Int,
    val onClick: () -> Unit,
)

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomePage(
    navigator: HomeNavigator,
    editViewModel: EventEditBottomSheetViewModel = hiltViewModel(),
    homeViewModel: HomeViewModel = hiltViewModel(),
) {
    val todayEventId = homeViewModel.todayEventId.collectAsStateWithLifecycle()
    val bottomBarItems = rememberBottomBarItems(
        onYearlyFollowUp = {
            navigator.navigateToYearSummary()
        },
        onMonthlyStatFollowUp = {
            navigator.navigateToReport()
        },
        onMonthlyListFollowUp = {
            navigator.navigateToMonthSummary()
        },
    )
    val selectedItem = remember {
        derivedStateOf {
            when (navigator.backStack.last()) {
                is YearSummaryDestination -> 0
                is ReportDestination -> 1
                is MonthSummaryDestination -> 2
                else -> -1
            }
        }
    }
    val displayLegendAction = remember {
        derivedStateOf {
            when (navigator.backStack.lastOrNull()) {
                is ReportDestination -> true
                else -> false
            }
        }
    }
    val displayLegendPopup = remember {
        mutableStateOf(false)
    }

    HomePageContent(
        modifier = Modifier.fillMaxSize(),
        navigator = navigator,
        todayEventId = todayEventId,
        displayLegendAction = displayLegendAction,
        displayLegendPopup = displayLegendPopup,
        items = bottomBarItems,
        selectedItem = selectedItem,
        onDisplayLegend = {
            displayLegendPopup.value = true
        },
        onDismissLegend = {
            displayLegendPopup.value = false
        },
        onFabClick = {
            editViewModel.show(eventId = it)
        },
    )

    EventEditBottomSheet(
        viewModel = editViewModel,
        onDismissRequest = { editViewModel.dismiss() },
    )
}

@Composable
private fun rememberBottomBarItems(
    onYearlyFollowUp: () -> Unit,
    onMonthlyStatFollowUp: () -> Unit,
    onMonthlyListFollowUp: () -> Unit,
): List<BottomBarItemUio> = remember {
    listOf(
        BottomBarItemUio(
            selectedIcon = R.drawable.ic_calendar_month_filled_24dp,
            unselectedIcon = R.drawable.ic_calendar_month_24dp,
            onClick = onYearlyFollowUp,
        ),
        BottomBarItemUio(
            selectedIcon = R.drawable.ic_analytics_filled_24dp,
            unselectedIcon = R.drawable.ic_analytics_24dp,
            onClick = onMonthlyStatFollowUp,
        ),
        BottomBarItemUio(
            selectedIcon = R.drawable.ic_list_alt_filled_24dp,
            unselectedIcon = R.drawable.ic_list_alt_24dp,
            onClick = onMonthlyListFollowUp,
        )
    )
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun HomePageContent(
    modifier: Modifier = Modifier,
    navigator: HomeNavigator,
    displayLegendAction: State<Boolean>,
    displayLegendPopup: State<Boolean>,
    todayEventId: State<Long?>,
    items: List<BottomBarItemUio>,
    selectedItem: State<Int>,
    onDisplayLegend: () -> Unit,
    onDismissLegend: () -> Unit,
    onFabClick: (Long?) -> Unit,
) {
    Scaffold(
        modifier = modifier,
        topBar = {
            Toolbar(
                title = {
                    val title = remember {
                        val format = SimpleDateFormat("EEEE dd MMMM", Locale.getDefault())
                        format.format(System.currentTimeMillis())
                    }
                    Text(
                        text = title.capitalize(),
                    )
                },
                actions = {
                    AnimatedVisibility(
                        visible = displayLegendAction.value,
                    ) {
                        AnimatedContent(
                            targetState = displayLegendPopup.value,
                            transitionSpec = { fadeIn() togetherWith fadeOut() },
                        ) { display ->
                            IconButton(
                                onClick = onDisplayLegend,
                            ) {
                                Icon(
                                    imageVector = when (display) {
                                        true -> Icons.Filled.Info
                                        else -> Icons.Outlined.Info
                                    },
                                    contentDescription = null,
                                )
                            }
                        }
                        DropdownMenu(
                            expanded = displayLegendPopup.value,
                            onDismissRequest = onDismissLegend,
                        ) {
                            LegendPopupContent(
                                modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp)
                            )
                        }
                    }
                }
            )
        },
        bottomBar = {
            NavigationBar {
                items.forEachIndexed { index, item ->
                    NavigationBarItem(
                        icon = {
                            AnimatedContent(
                                targetState = selectedItem.value,
                                transitionSpec = { fadeIn() togetherWith fadeOut() },
                            ) {
                                Icon(
                                    painter = painterResource(
                                        when (it) {
                                            index -> item.selectedIcon
                                            else -> item.unselectedIcon
                                        }
                                    ),
                                    contentDescription = null,
                                )
                            }
                        },
                        selected = selectedItem.value == index,
                        onClick = item.onClick,
                    )
                }
            }
        },
        floatingActionButton = {
            AnimatedContent(
                targetState = todayEventId.value,
                transitionSpec = { fadeIn() togetherWith fadeOut() },
            ) {
                FloatingActionButton(
                    containerColor = MaterialTheme.colorScheme.primary,
                    shape = CircleShape,
                    onClick = { onFabClick(todayEventId.value) },
                ) {
                    Icon(
                        imageVector = when (it) {
                            null -> Icons.Default.Add
                            else -> Icons.Default.Edit
                        },
                        contentDescription = null,
                    )
                }
            }
        },
        content = { paddingValues ->
            HomeNavDisplay(
                modifier = Modifier.padding(paddingValues = paddingValues),
                navigator = navigator,
            )
        }
    )
}

@Composable
private fun LegendPopupContent(
    modifier: Modifier = Modifier,
) {
    Column(
        modifier = modifier,
    ) {
        Row(
            horizontalArrangement = Arrangement.spacedBy(space = 4.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Box(
                modifier = Modifier
                    .size(8.dp)
                    .background(
                        color = HeadacheColorPalette.Calendar.Headache,
                    )
            )
            Text(
                style = MaterialTheme.typography.labelSmall,
                text = "Jours de migraine",
            )
        }
        Row(
            horizontalArrangement = Arrangement.spacedBy(space = 4.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Box(
                modifier = Modifier
                    .size(8.dp)
                    .background(
                        color = HeadacheColorPalette.Calendar.Pill,
                    )
            )
            Text(
                style = MaterialTheme.typography.labelSmall,
                text = "Prise de cachet",
            )
        }
    }
}