package com.laseroptek.raman.utils

import android.content.Context
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
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.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
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.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader

// Helper function to read content from URI
suspend fun readFileFromUri(
    context: Context,
    uri: Uri
): String? { // Returns String content, or null on failure
    return withContext(Dispatchers.IO) {
        try {
            context.contentResolver.openInputStream(uri)?.use { inputStream ->
                BufferedReader(InputStreamReader(inputStream)).use { reader ->
                    reader.readText() // Reads entire content as String
                }
            } ?: run {
                Timber.e("Failed to open input stream for URI: $uri")
                null
            }
        } catch (e: IOException) {
            Timber.e(e, "Error reading file from $uri")
            null
        }
    }
}


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ImportFileFromUsbScreen(
    modifier: Modifier = Modifier,
    snackbarHostState: SnackbarHostState = remember { SnackbarHostState() },
    coroutineScope: CoroutineScope = rememberCoroutineScope()
) {
    val context = LocalContext.current
    var isLoading by remember { mutableStateOf(false) }
    var fileContentPreview by remember { mutableStateOf<String?>(null) } // To show a snippet of imported content

    val openFileLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.OpenDocument(), // Contract for opening an existing document
        onResult = { uri: Uri? ->
            uri?.let { selectedUri ->
                isLoading = true
                fileContentPreview = null // Clear previous preview
                coroutineScope.launch {
                    val content = readFileFromUri(context, selectedUri)
                    isLoading = false
                    if (content != null) {
                        fileContentPreview = content.take(200) // Show first 200 chars as preview
                        snackbarHostState.showSnackbar("File imported successfully!", duration = SnackbarDuration.Short)
                        Timber.d("File content loaded from $selectedUri")
                        // TODO: Process the full 'content' as needed (e.g., parse JSON, update database, etc.)
                    } else {
                        snackbarHostState.showSnackbar("Failed to read file.", duration = SnackbarDuration.Short)
                    }
                }
            } ?: run {
                Timber.d("Import cancelled by user.")
                coroutineScope.launch {
                    snackbarHostState.showSnackbar("Import cancelled.", duration = SnackbarDuration.Short)
                }
            }
        }
    )

    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        if (isLoading) {
            CircularProgressIndicator()
            Spacer(modifier = Modifier.height(16.dp))
            Text("Importing...")
        } else {
            Button(
                onClick = {
                    // Launch the file picker, filtering for text files.
                    // You can specify multiple MIME types: arrayOf("text/plain", "application/json")
                    openFileLauncher.launch(arrayOf("text/plain", "*/*")) // Example: text files or any file
                },
                modifier = Modifier.fillMaxWidth()
            ) {
                Text("Import Text File from USB/External")
            }

            fileContentPreview?.let {
                Spacer(modifier = Modifier.height(24.dp))
                Text("File Preview (first 200 chars):", style = MaterialTheme.typography.titleMedium)
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = it,
                    style = MaterialTheme.typography.bodySmall,
                    maxLines = 10,
                    modifier = Modifier
                        .fillMaxWidth()
                        .heightIn(max = 200.dp) // Limit preview height
                )
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Preview(showBackground = true)
@Composable
fun ImportFileFromUsbScreenPreview() {
    // Initialize Timber for Preview if not already done in an Application class
    // Timber.plant(Timber.DebugTree())

    val snackbarHostState = remember { SnackbarHostState() }
    val coroutineScope = rememberCoroutineScope()

    MaterialTheme {
        Scaffold(
            snackbarHost = { SnackbarHost(snackbarHostState) },
            topBar = { TopAppBar(title = { Text("Import File Demo") }) }
        ) { paddingValues ->
            ImportFileFromUsbScreen(
                modifier = Modifier.padding(paddingValues),
                snackbarHostState = snackbarHostState,
                coroutineScope = coroutineScope
            )
        }
    }
}