package com.isidroid.c23.ui.screen.content

import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
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.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.isidroid.c23.R
import com.isidroid.c23.ui._component.ShortOfficeInfoComponent
import com.isidroid.c23.ui._component.TopAppBarComponent
import com.isidroid.core.vm.SIDE_EFFECTS_KEY
import kotlinx.coroutines.flow.Flow

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ContentScreen(
    state: State<ContentContract.State>,
    effectFlow: Flow<ContentContract.Effect>?,
    onEventSent: (event: ContentContract.Event) -> Unit,
    onNavigationRequested: (navigationEffect: ContentContract.Effect.Navigation) -> Unit,
    modifier: Modifier = Modifier
) {
    val launcher = rememberLauncherForActivityResult(ActivityResultContracts.GetMultipleContents()) { uris ->
        onEventSent(ContentContract.Event.MultipleContents(uris))
    }

    BackHandler {
        onEventSent(ContentContract.Event.GoBack)
    }

    LaunchedEffect(state.value.galleryHash) { if (state.value.galleryHash != null) launcher.launch("image/*") }
    LaunchedEffect(state.value.documentHash) { if (state.value.documentHash != null) launcher.launch("document/pdf") }
    LaunchedEffect(SIDE_EFFECTS_KEY) {
        effectFlow?.collect { effect ->
            when (effect) {
                is ContentContract.Effect.Navigation -> onNavigationRequested(effect)
            }
        }
    }

    Scaffold(
        modifier = modifier.fillMaxSize(),
        topBar = {
            TopAppBarComponent(
                text = stringResource(id = R.string.select_content),
                colors = TopAppBarDefaults.topAppBarColors(
//                    containerColor = MaterialTheme.colorScheme.primary,
//                    titleContentColor = MaterialTheme.colorScheme.onPrimary
                )
            )
        }
    ) { paddingValues ->
        Column(modifier = Modifier.fillMaxSize()) {
            Row(
                Modifier
                    .padding(paddingValues)
                    .fillMaxWidth()
            ) {
                BlockComponent(
                    text = stringResource(id = R.string.select_content_photos),
                    image = painterResource(id = R.drawable.content_type_photo),
                    onClick = { onEventSent(ContentContract.Event.PickContent(photo = true)) },
                )

                BlockComponent(
                    text = stringResource(id = R.string.select_content_doc),
                    image = painterResource(id = R.drawable.content_type_doc),
                    onClick = { onEventSent(ContentContract.Event.PickContent(documents = true)) },
                )
            }


            Spacer(modifier = Modifier.weight(1f))
            Footer(state, paddingValues, onEventSent)
        }
    }
}

@Composable
private fun Footer(
    state: State<ContentContract.State>,
    paddingValues: PaddingValues,
    onEventSent: (event: ContentContract.Event) -> Unit
) {
    val richSpot = state.value.richSpot ?: return

    ShortOfficeInfoComponent(
        officeName = richSpot.spot.name,
        modifier = Modifier.fillMaxWidth(),
        containerClick = { onEventSent(ContentContract.Event.OpenMap()) },
        buttonClick = null,
        titleRes = R.string.select_content_footer_title,
        buttonTextRes = R.string.app_name,
        paddingBottom = paddingValues.calculateBottomPadding(),
    )
}

@Composable
private fun RowScope.BlockComponent(
    text: String,
    image: Painter,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
) {
    Box(modifier = modifier
        .weight(1f)
        .height(160.dp)
        .padding(2.dp)
        .clip(RoundedCornerShape(6.dp))
        .clickable { onClick() }
    ) {

        Image(
            painter = image,
            contentDescription = null,
            modifier = Modifier.fillMaxSize(),
            contentScale = ContentScale.Crop
        )

        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(36.dp)
                .background(Color.Black.copy(alpha = .65f))
        ) {

            Text(
                text = text,
                color = Color.White,
                modifier = Modifier.padding(start = 16.dp, top = 2.dp),
                fontSize = 16.sp,
                style = MaterialTheme.typography.headlineSmall,
                letterSpacing = .96.sp,
                fontWeight = FontWeight.Medium
            )
        }
    }
}

@Composable
@Preview
private fun BlockPreview() {
    Surface {
        Row {
            BlockComponent(
                text = "Photos",
                image = painterResource(id = R.drawable.content_type_photo),
                onClick = { }
            )
        }
    }
}