/*
 * 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 androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
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.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
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 androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import com.pico.spatial.ui.design.ButtonChip
import com.pico.spatial.ui.design.Icon
import com.pico.spatial.ui.design.PicoTheme
import com.pico.spatial.ui.design.RemovableChip
import com.pico.spatial.ui.design.SearchField
import com.pico.spatial.ui.design.Text
import com.pico.spatial.ui.design.ToggleableChip
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.model.CardData
import com.pico.spatialui.sample.viewmodel.SearchViewModel

@Composable
fun SearchPage(searchViewModel: SearchViewModel = viewModel()) {
    Row(modifier = Modifier.fillMaxSize()) {
        Column(modifier = Modifier.width(346.dp).padding(12.dp)) {
            val searchText by searchViewModel.searchText.collectAsStateWithLifecycle()
            SearchField(
                modifier = Modifier.padding(24.dp),
                value = searchText,
                onValueChange = { searchViewModel.onSearchTextChange(it) },
                onSearch = {},
                placeholder = {
                    Text(
                        text = stringResource(R.string.sui_sample_search),
                        style = PicoTheme.typography.bodyLarge
                    )
                }
            )

            val recommendedList by
                searchViewModel.searchKeyRecommendedList.collectAsStateWithLifecycle()
            if (recommendedList.isNotEmpty()) {
                FlowRow(
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp),
                    modifier = Modifier.padding(start = 24.dp, end = 24.dp)
                ) {
                    for (item in recommendedList) {
                        key(item) {
                            RemovableChip(
                                label = {
                                    Text(
                                        stringResource(item),
                                        style = PicoTheme.typography.labelMedium
                                    )
                                },
                                onLeadingClick = {},
                                onTrailingRemoveClick = {
                                    searchViewModel.removeKeyFromRecommendedList(item)
                                },
                                visible = true,
                                enabled = true
                            )
                        }
                    }
                }
            }

            Spacer(Modifier.height(24.dp))

            Text(
                text = stringResource(R.string.sui_sample_have_guess),
                modifier = Modifier.padding(start = 24.dp, end = 24.dp),
                style = PicoTheme.typography.titleSmall
            )

            Spacer(Modifier.height(14.dp))

            val suggestionList by searchViewModel.suggestionList.collectAsStateWithLifecycle()
            FlowRow(
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp),
                modifier = Modifier.padding(start = 24.dp, end = 24.dp)
            ) {
                for (item in suggestionList) {
                    key(item.valueRes) {
                        ButtonChip(
                            label = {
                                Text(
                                    stringResource(item.valueRes),
                                    style = PicoTheme.typography.labelMedium
                                )
                            },
                            onClick = {},
                            leadingIcon = {
                                if (item.hot) {
                                    Icon(
                                        painter = painterResource(R.drawable.fire),
                                        contentDescription = "",
                                        tint = Color.Red.withVibrant(Vibrant.None),
                                    )
                                }
                            }
                        )
                    }
                }
            }
        }

        Column(
            modifier =
                Modifier.weight(1f).background(color = Color.Vibrant.withVibrant(Vibrant.Light))
        ) {
            Text(
                text = stringResource(R.string.sui_sample_search_result),
                modifier = Modifier.padding(32.dp),
                style = PicoTheme.typography.titleLarge
            )

            val categoryList by searchViewModel.categoryList.collectAsStateWithLifecycle()
            FlowRow(
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                modifier = Modifier.padding(start = 32.dp, end = 32.dp)
            ) {
                categoryList.forEach { category ->
                    key(category.nameRes) {
                        ToggleableChip(
                            label = {
                                Text(
                                    stringResource(category.nameRes),
                                    style = PicoTheme.typography.labelMedium
                                )
                            },
                            isToggleOn = category.isSelected,
                            onClick = { searchViewModel.toggleCategorySelection(category.nameRes) },
                        )
                    }
                }
            }
            Spacer(Modifier.height(20.dp))

            val ratio = 286.67f / 259.5f
            val searchResultList by searchViewModel.searchResultList.collectAsStateWithLifecycle()
            LazyVerticalGrid(
                columns = GridCells.Fixed(3),
                modifier = Modifier.padding(start = 32.dp, end = 32.dp).weight(1f),
                verticalArrangement = Arrangement.spacedBy(20.dp),
                horizontalArrangement = Arrangement.spacedBy(20.dp)
            ) {
                items(items = searchResultList, key = CardData::id) { cardData ->
                    AsyncImage(
                        model = cardData.imageId,
                        contentDescription = cardData.imageDescription,
                        modifier =
                            Modifier.fillMaxWidth()
                                .aspectRatio(ratio = ratio)
                                .clip(RoundedCornerShape(8.dp)),
                        contentScale = ContentScale.Crop
                    )
                }
            }

            Spacer(Modifier.height(32.dp))
        }
    }
}

@Preview(showBackground = false, widthDp = 1280, heightDp = 720)
@Composable
fun SearchPagePreview() {
    PicoTheme { SearchPage() }
}
