package com.tt.honeyDue.ui.components

import android.net.Uri
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.platform.LocalContext
import com.tt.honeyDue.models.Contractor
import com.tt.honeyDue.models.SharedContractor
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.sharing.ContractorSharingManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json

/**
 * Represents the current state of the contractor import flow.
 */
sealed class ImportState {
    data object Idle : ImportState()
    data class Confirmation(val sharedContractor: SharedContractor) : ImportState()
    data class Importing(val sharedContractor: SharedContractor) : ImportState()
    data class Success(val contractorName: String) : ImportState()
    data class Error(val message: String) : ImportState()
}

/**
 * Android-specific composable that handles the contractor import flow.
 * Shows confirmation dialog, performs import, and displays result.
 *
 * @param pendingImportUri The URI of the .honeydue file to import (or null if none)
 * @param onClearImport Called when import flow is complete and URI should be cleared
 * @param onImportSuccess Called when import succeeds, with the imported contractor
 */
@Composable
fun ContractorImportHandler(
    pendingImportUri: Uri?,
    onClearImport: () -> Unit,
    onImportSuccess: (Contractor) -> Unit = {}
) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()

    var importState by remember { mutableStateOf<ImportState>(ImportState.Idle) }
    var pendingUri by remember { mutableStateOf<Uri?>(null) }
    var importedContractor by remember { mutableStateOf<Contractor?>(null) }

    val json = remember {
        Json {
            ignoreUnknownKeys = true
            encodeDefaults = true
        }
    }

    // Parse the .honeydue file when a new URI is received
    LaunchedEffect(pendingImportUri) {
        if (pendingImportUri != null && importState is ImportState.Idle) {
            pendingUri = pendingImportUri

            withContext(Dispatchers.IO) {
                try {
                    val inputStream = context.contentResolver.openInputStream(pendingImportUri)
                    if (inputStream != null) {
                        val jsonString = inputStream.bufferedReader().use { it.readText() }
                        inputStream.close()

                        val sharedContractor = json.decodeFromString(
                            SharedContractor.serializer(),
                            jsonString
                        )
                        withContext(Dispatchers.Main) {
                            importState = ImportState.Confirmation(sharedContractor)
                        }
                    } else {
                        withContext(Dispatchers.Main) {
                            importState = ImportState.Error("Could not open file")
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    withContext(Dispatchers.Main) {
                        importState = ImportState.Error("Invalid contractor file: ${e.message}")
                    }
                }
            }
        }
    }

    // Show appropriate dialog based on state
    when (val state = importState) {
        is ImportState.Idle -> {
            // No dialog
        }

        is ImportState.Confirmation -> {
            ContractorImportConfirmDialog(
                sharedContractor = state.sharedContractor,
                isImporting = false,
                onConfirm = {
                    importState = ImportState.Importing(state.sharedContractor)
                    scope.launch {
                        pendingUri?.let { uri ->
                            when (val result = ContractorSharingManager.importContractor(context, uri)) {
                                is ApiResult.Success -> {
                                    importedContractor = result.data
                                    importState = ImportState.Success(result.data.name)
                                }
                                is ApiResult.Error -> {
                                    importState = ImportState.Error(result.message)
                                }
                                else -> {
                                    importState = ImportState.Error("Import failed unexpectedly")
                                }
                            }
                        }
                    }
                },
                onDismiss = {
                    importState = ImportState.Idle
                    pendingUri = null
                    onClearImport()
                }
            )
        }

        is ImportState.Importing -> {
            // Show the confirmation dialog with loading state
            ContractorImportConfirmDialog(
                sharedContractor = state.sharedContractor,
                isImporting = true,
                onConfirm = {},
                onDismiss = {}
            )
        }

        is ImportState.Success -> {
            ContractorImportSuccessDialog(
                contractorName = state.contractorName,
                onDismiss = {
                    importedContractor?.let { onImportSuccess(it) }
                    importState = ImportState.Idle
                    pendingUri = null
                    importedContractor = null
                    onClearImport()
                }
            )
        }

        is ImportState.Error -> {
            ContractorImportErrorDialog(
                errorMessage = state.message,
                onRetry = pendingUri?.let { uri ->
                    {
                        // Retry by re-parsing the file
                        scope.launch {
                            withContext(Dispatchers.IO) {
                                try {
                                    val inputStream = context.contentResolver.openInputStream(uri)
                                    if (inputStream != null) {
                                        val jsonString = inputStream.bufferedReader().use { it.readText() }
                                        inputStream.close()
                                        val sharedContractor = json.decodeFromString(
                                            SharedContractor.serializer(),
                                            jsonString
                                        )
                                        withContext(Dispatchers.Main) {
                                            importState = ImportState.Confirmation(sharedContractor)
                                        }
                                    }
                                } catch (e: Exception) {
                                    // Keep showing error
                                }
                            }
                        }
                    }
                },
                onDismiss = {
                    importState = ImportState.Idle
                    pendingUri = null
                    onClearImport()
                }
            )
        }
    }
}
