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.JoinResidenceResponse
import com.tt.honeyDue.models.SharedResidence
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.sharing.ResidenceSharingManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json

/**
 * Represents the current state of the residence import flow.
 */
sealed class ResidenceImportState {
    data object Idle : ResidenceImportState()
    data class Confirmation(val sharedResidence: SharedResidence) : ResidenceImportState()
    data class Importing(val sharedResidence: SharedResidence) : ResidenceImportState()
    data class Success(val residenceName: String) : ResidenceImportState()
    data class Error(val message: String) : ResidenceImportState()
}

/**
 * Android-specific composable that handles the residence 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 join response
 */
@Composable
fun ResidenceImportHandler(
    pendingImportUri: Uri?,
    onClearImport: () -> Unit,
    onImportSuccess: (JoinResidenceResponse) -> Unit = {}
) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()

    var importState by remember { mutableStateOf<ResidenceImportState>(ResidenceImportState.Idle) }
    var pendingUri by remember { mutableStateOf<Uri?>(null) }
    var importedResponse by remember { mutableStateOf<JoinResidenceResponse?>(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 ResidenceImportState.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 sharedResidence = json.decodeFromString(
                            SharedResidence.serializer(),
                            jsonString
                        )
                        withContext(Dispatchers.Main) {
                            importState = ResidenceImportState.Confirmation(sharedResidence)
                        }
                    } else {
                        withContext(Dispatchers.Main) {
                            importState = ResidenceImportState.Error("Could not open file")
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    withContext(Dispatchers.Main) {
                        importState = ResidenceImportState.Error("Invalid residence file: ${e.message}")
                    }
                }
            }
        }
    }

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

        is ResidenceImportState.Confirmation -> {
            ResidenceImportConfirmDialog(
                sharedResidence = state.sharedResidence,
                isImporting = false,
                onConfirm = {
                    importState = ResidenceImportState.Importing(state.sharedResidence)
                    scope.launch {
                        pendingUri?.let { uri ->
                            when (val result = ResidenceSharingManager.importResidence(context, uri)) {
                                is ApiResult.Success -> {
                                    importedResponse = result.data
                                    importState = ResidenceImportState.Success(result.data.residence.name)
                                }
                                is ApiResult.Error -> {
                                    importState = ResidenceImportState.Error(result.message)
                                }
                                else -> {
                                    importState = ResidenceImportState.Error("Import failed unexpectedly")
                                }
                            }
                        }
                    }
                },
                onDismiss = {
                    importState = ResidenceImportState.Idle
                    pendingUri = null
                    onClearImport()
                }
            )
        }

        is ResidenceImportState.Importing -> {
            // Show the confirmation dialog with loading state
            ResidenceImportConfirmDialog(
                sharedResidence = state.sharedResidence,
                isImporting = true,
                onConfirm = {},
                onDismiss = {}
            )
        }

        is ResidenceImportState.Success -> {
            ResidenceImportSuccessDialog(
                residenceName = state.residenceName,
                onDismiss = {
                    importedResponse?.let { onImportSuccess(it) }
                    importState = ResidenceImportState.Idle
                    pendingUri = null
                    importedResponse = null
                    onClearImport()
                }
            )
        }

        is ResidenceImportState.Error -> {
            ResidenceImportErrorDialog(
                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 sharedResidence = json.decodeFromString(
                                            SharedResidence.serializer(),
                                            jsonString
                                        )
                                        withContext(Dispatchers.Main) {
                                            importState = ResidenceImportState.Confirmation(sharedResidence)
                                        }
                                    }
                                } catch (e: Exception) {
                                    // Keep showing error
                                }
                            }
                        }
                    }
                },
                onDismiss = {
                    importState = ResidenceImportState.Idle
                    pendingUri = null
                    onClearImport()
                }
            )
        }
    }
}
