package com.tt.honeyDue.platform

import android.content.Intent
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.platform.LocalContext
import com.tt.honeyDue.models.Residence
import com.tt.honeyDue.sharing.ResidenceSharingManager
import com.tt.honeyDue.analytics.PostHogAnalytics
import com.tt.honeyDue.analytics.AnalyticsEvents
import kotlinx.coroutines.launch

@Composable
actual fun rememberShareResidence(): Pair<ResidenceSharingState, (Residence) -> Unit> {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    var state by remember { mutableStateOf(ResidenceSharingState()) }

    val shareFunction: (Residence) -> Unit = { residence ->
        scope.launch {
            state = ResidenceSharingState(isLoading = true)

            val intent = ResidenceSharingManager.createShareIntent(context, residence)
            if (intent != null) {
                state = ResidenceSharingState(isLoading = false)
                // Track residence shared event
                PostHogAnalytics.capture(
                    AnalyticsEvents.RESIDENCE_SHARED,
                    mapOf("method" to "file")
                )
                context.startActivity(Intent.createChooser(intent, "Share Residence"))
            } else {
                state = ResidenceSharingState(
                    isLoading = false,
                    error = "Failed to generate share package"
                )
            }
        }
    }

    return Pair(state, shareFunction)
}
