package com.laseroptek.raman.ui.screens.engineer.export

import android.content.res.Configuration
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
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.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.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.laseroptek.raman.R
import com.laseroptek.raman.repository.datastore
import com.laseroptek.raman.ui.MainActivity
import com.laseroptek.raman.ui.common.fullscreen.FullScreen
import com.laseroptek.raman.ui.theme.RobotoTypography
import com.laseroptek.raman.utils.PreferenceBackupManager
import com.laseroptek.raman.utils.ext.dropShadow
import com.laseroptek.raman.utils.ext.px
import kotlinx.coroutines.launch
import timber.log.Timber
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale


@Composable
fun ExportConfirmPopup(
    title: String = stringResource(R.string.export_confirm_title),
    onClick: (Boolean) -> Unit= {}
) {
    FullScreen {
        val context = LocalContext.current
        val activity = LocalContext.current as? MainActivity

        var isLoading by remember { mutableStateOf(false) }
        //val snackbarHostState = remember { SnackbarHostState() }
        val coroutineScope = rememberCoroutineScope()

        val preferenceBackupManager = PreferenceBackupManager(context, context.datastore)

        val createFileLauncher = rememberLauncherForActivityResult(
            contract = ActivityResultContracts.CreateDocument("application/json"), // MIME type for a text file
            onResult = { uri: Uri? ->
                uri?.let { selectedUri ->
                    // Get a reference to the MainActivity to call its public functions
                    //activity?.setSystemBarsVisible(false)

                    isLoading = true
                    coroutineScope.launch {
                        val success = preferenceBackupManager.exportPreferencesToUri(
                            uri = selectedUri
                        )
                        isLoading = false
                        val message = if (success) "File exported successfully!" else "Export failed."
                        //snackbarHostState.showSnackbar(message, duration = SnackbarDuration.Short)
                        Timber.d("Export result: $success to $selectedUri")
                        onClick(true)
                    }
                } ?: run {
                    Timber.d("Export cancelled by user.")

                    //coroutineScope.launch {
                    //    snackbarHostState.showSnackbar("Export cancelled.", duration = SnackbarDuration.Short)
                    //}

                    onClick(false)
                }
            }
        )

        Column(
            modifier = Modifier
                .size(312.px.dp, 132.px.dp)
                .clip(RoundedCornerShape(28.px.dp))
                .background(Color.White)
                .dropShadow(
                    shape = RoundedCornerShape(28.px.dp),
                    color = Color.Black.copy(alpha = 0.1f),
                    blur = 48.px.dp,
                    offsetX = 0.px.dp,
                    offsetY = 24.px.dp,
                    spread = 0.px.dp
                )
                .dropShadow(
                    shape = RoundedCornerShape(28.px.dp),
                    color = Color.Black.copy(alpha = 0.1f),
                    blur = 6.px.dp,
                    offsetX = 0.px.dp,
                    offsetY = 3.px.dp,
                    spread = 0.px.dp
                ),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center,
        ) {
            // Title
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(64.px.dp)
                    .padding(start = 40.px.dp, end = 40.px.dp),
                horizontalArrangement = Arrangement.Start,
                verticalAlignment = Alignment.Bottom
            ) {
                Text(
                    text = title,
                    style = RobotoTypography.bodySmall,
                    fontWeight = FontWeight.Normal,
                    fontSize = 14.px.sp,
                    color = Color.Black,
                    textAlign = TextAlign.Start,
                    lineHeight = 20.px.sp
                )
            }

            // Two Button
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(68.px.dp),
                horizontalArrangement = Arrangement.End,
                verticalAlignment = Alignment.CenterVertically
            ) {
                if (isLoading) {
                    CircularProgressIndicator()
                    Spacer(modifier = Modifier.height(16.dp))
                    Text("Exporting...")
                } else {
                    // Cancel
                    TextButton(
                        modifier = Modifier
                            .size(68.px.dp, 40.px.dp),
                        onClick = {
                            Timber.d("Cancel Clicked")
                            onClick(false)
                        }
                    ) {
                        Text(
                            text = stringResource(R.string.cancel),
                            style = RobotoTypography.labelLarge,
                            fontWeight = FontWeight.Normal,
                            fontSize = 14.px.sp,
                            color = Color.Black
                        )
                    }

                    // Ok
                    TextButton(
                        modifier = Modifier
                            .size(68.px.dp, 40.px.dp),
                        onClick = {
                            Timber.d("Ok Clicked")

                            // Before launching the system UI, show the navigation bar.
                            //activity?.setSystemBarsVisible(true)

                            val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
                            val fileName = "export_$timestamp" // Suggest a .txt extension
                            createFileLauncher.launch(fileName)
                        }
                    ) {
                        Text(
                            text = stringResource(R.string.ok),
                            style = RobotoTypography.labelLarge,
                            fontWeight = FontWeight.Normal,
                            fontSize = 14.px.sp,
                            color = Color.Black
                        )
                    }
                }
            }
        }
    }
}


@Preview(
    uiMode = Configuration.UI_MODE_NIGHT_NO,
    showBackground = false
)
@Composable
fun PreviewExportConfirmPopup() {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
    ){
        ExportConfirmPopup(
            title = stringResource(R.string.export_confirm_title),
        )
    }

}