/*
 * 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.content.Context
import androidx.annotation.DrawableRes
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.LayoutDirection
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.pico.spatial.ui.design.Icon
import com.pico.spatial.ui.design.LocalContentColor
import com.pico.spatial.ui.design.Text
import com.pico.spatial.ui.design.windows.TabBar
import com.pico.spatial.ui.platform.ViewPoint
import com.pico.spatialui.sample.R
import com.pico.spatialui.sample.pages.userpage.UserPage
import com.pico.spatialui.sample.router.AppGraphRouter
import com.pico.spatialui.sample.router.AppGraphRouter.buildDetailRoute

data class TabData(@DrawableRes val iconId: Int, val text: String, val route: String)

fun buildTabDataList(context: Context) =
    listOf(
        TabData(
            R.drawable.feeds,
            context.getString(R.string.sui_sample_recommended),
            AppGraphRouter.FEEDS
        ),
        TabData(
            R.drawable.search,
            context.getString(R.string.sui_sample_search),
            AppGraphRouter.SEARCH
        ),
        TabData(
            R.drawable.ic_user_center,
            context.getString(R.string.sui_sample_user_center),
            AppGraphRouter.USER
        )
    )

@Composable
fun AppTabBar(
    list: List<TabData>,
    currentRoute: String,
    isRTL: Boolean,
    onItemClick: (targetRoute: String) -> Unit
) {
    TabBar(
        followViewpoints = setOf(
            ViewPoint.Front,
            if (isRTL) ViewPoint.Right else ViewPoint.Left
        )
    ) {
        list.forEachIndexed { index,itemData ->
            item(
                selected = (currentRoute == itemData.route),
                onClick = { onItemClick(itemData.route) },
                mainContent = {
                    Icon(
                        painter = painterResource(itemData.iconId),
                        contentDescription = itemData.text,
                        tint = if (index == 2) Color.Unspecified else LocalContentColor.current
                    )
                },
                supportContent = {
                    Text(text = itemData.text)
                }
            )
        }
    }
}

@Composable
fun HomePage(modifier: Modifier) {
    val navController = rememberNavController()

    val navBackStackEntry by navController.currentBackStackEntryAsState()
    val currentRoute = navBackStackEntry?.destination?.route ?: AppGraphRouter.FEEDS

    val context = LocalContext.current
    val tabDataList = remember(context) { buildTabDataList(context) }

    val showTabBar =
        remember(currentRoute, tabDataList) { tabDataList.any { it.route == currentRoute } }

    val layoutDirection = LocalLayoutDirection.current
    val isRTL = remember(layoutDirection) {
        layoutDirection == LayoutDirection.Rtl
    }

    Box(modifier = modifier.fillMaxSize()) {
        NavHost(navController = navController, startDestination = AppGraphRouter.FEEDS) {
            composable(AppGraphRouter.FEEDS) {
                FeedsPage(feedsViewModel = viewModel()) { id ->
                    navController.navigate(buildDetailRoute(id))
                }
            }

            composable(AppGraphRouter.SEARCH) { SearchPage(searchViewModel = viewModel()) }

            composable(AppGraphRouter.USER) { UserPage() }

            composable(AppGraphRouter.DETAIL) { backStackEntry ->
                val itemId = backStackEntry.arguments?.getString(AppGraphRouter.ARG_ITEM_ID) ?: ""
                ContentDetailPage(itemId) {
                    if (navController.previousBackStackEntry != null) {
                        navController.popBackStack()
                    }
                }
            }
        }

        if (showTabBar) {
            AppTabBar(
                list = tabDataList,
                currentRoute = currentRoute,
                isRTL = isRTL
            ) { targetRoute ->
                if (currentRoute != targetRoute) {
                    navController.navigate(targetRoute) {
                        popUpTo(navController.graph.startDestinationId) { saveState = true }
                        launchSingleTop = true
                        restoreState = true
                    }
                }
            }
        }
    }
}
