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

import android.Manifest
import android.os.Build
import androidx.activity.compose.BackHandler
import androidx.activity.compose.ManagedActivityResultLauncher
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.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.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ShoppingCart
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
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.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
import timber.log.Timber

@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))
    }

    val notificationLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) {
        onEventSent(ContentContract.Event.CheckNotificationPermission)
    }

    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("application/pdf") }
    LaunchedEffect(state.value.wordHash) { if (state.value.wordHash != null) launcher.launch("application/msword") }
    LaunchedEffect("not_perm_${state.value.hasNotificationPermission}") { if (state.value.hasNotificationPermission == false) notificationLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) }


    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(),
                actions = { TopBarActions(onEventSent) }
            )
        },

        ) { paddingValues ->
        Column(modifier = Modifier.fillMaxSize()) {
            LazyVerticalGrid(
                columns = GridCells.Fixed(2),
                Modifier
                    .padding(paddingValues)
                    .fillMaxWidth()
            ) {
                item {
                    BlockComponent(
                        text = stringResource(id = R.string.select_content_photos),
                        image = painterResource(id = R.drawable.content_type_photo),
                        onClick = { onEventSent(ContentContract.Event.PickContent(photo = true)) },
                    )
                }

                item {
                    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 TopBarActions(onEventSent: (event: ContentContract.Event) -> Unit) {
    Icon(Icons.Rounded.ShoppingCart, contentDescription = null,
        modifier = Modifier.clickable { onEventSent(ContentContract.Event.ToPrintJobList) })
}

@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 BlockComponent(
    text: String,
    image: Painter,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
) {
    Box(modifier = modifier
        .fillMaxWidth()
        .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
            )
        }
    }
}
