package ru.forbion.f7cloud.feature.mail

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
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.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import ru.forbion.f7cloud.core.auth.AuthSession
import ru.forbion.f7cloud.core.designsystem.F7Colors
import ru.forbion.f7cloud.core.designsystem.F7Theme
import ru.forbion.f7cloud.core.network.UnauthorizedException
import ru.forbion.f7cloud.feature.files.FileItem
import ru.forbion.f7cloud.feature.files.FilesRepository

class MailFilesPickerActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val session = readSession() ?: run {
            finish()
            return
        }
        val mode = intent.getStringExtra(EXTRA_MODE) ?: MODE_ATTACHMENT
        val title = if (mode == MODE_SHARE_LINK) {
            "Ссылка из «Файлов»"
        } else {
            "Выбор файла"
        }
        setContent {
            F7Theme {
                MailFilesPickerScreen(
                    session = session,
                    title = title,
                    onCancel = { finish() },
                    onUnauthorized = { finish() },
                    onFileSelected = { file ->
                        setResult(
                            Activity.RESULT_OK,
                            Intent().apply {
                                putExtra(RESULT_PATH, "/${file.relativePath.trim('/')}")
                                putExtra(RESULT_NAME, file.name)
                                putExtra(RESULT_SIZE, file.size ?: 0L)
                                putExtra(RESULT_MIME, file.mimeType.orEmpty())
                            },
                        )
                        finish()
                    },
                )
            }
        }
    }

    private fun readSession(): AuthSession? {
        val username = intent.getStringExtra(EXTRA_USERNAME).orEmpty()
        val serverUrl = intent.getStringExtra(EXTRA_SERVER_URL).orEmpty()
        val password = intent.getStringExtra(EXTRA_PASSWORD).orEmpty()
        if (username.isBlank() || serverUrl.isBlank() || password.isBlank()) return null
        return AuthSession(
            serverUrl = serverUrl,
            username = username,
            appPassword = password,
            trustAllCerts = intent.getBooleanExtra(EXTRA_TRUST_ALL_CERTS, false),
        )
    }

    companion object {
        const val EXTRA_USERNAME = "username"
        const val EXTRA_PASSWORD = "password"
        const val EXTRA_SERVER_URL = "server_url"
        const val EXTRA_TRUST_ALL_CERTS = "trust_all_certs"
        const val EXTRA_MODE = "mode"
        const val MODE_ATTACHMENT = "attachment"
        const val MODE_SHARE_LINK = "share_link"
        const val RESULT_PATH = "result_path"
        const val RESULT_NAME = "result_name"
        const val RESULT_SIZE = "result_size"
        const val RESULT_MIME = "result_mime"

        fun intent(context: Context, session: AuthSession, mode: String): Intent =
            Intent(context, MailFilesPickerActivity::class.java).apply {
                putExtra(EXTRA_USERNAME, session.username)
                putExtra(EXTRA_PASSWORD, session.appPassword)
                putExtra(EXTRA_SERVER_URL, session.serverUrl)
                putExtra(EXTRA_TRUST_ALL_CERTS, session.trustAllCerts)
                putExtra(EXTRA_MODE, mode)
            }
    }
}

@Composable
private fun MailFilesPickerScreen(
    session: AuthSession,
    title: String,
    onCancel: () -> Unit,
    onUnauthorized: () -> Unit,
    onFileSelected: (FileItem) -> Unit,
) {
    val context = LocalContext.current
    val repository = remember { FilesRepository(context.applicationContext) }
    var currentPath by remember { mutableStateOf("") }
    var items by remember { mutableStateOf<List<FileItem>>(emptyList()) }
    var loading by remember { mutableStateOf(true) }
    var error by remember { mutableStateOf<String?>(null) }
    val base = session.serverUrl.trimEnd('/')

    LaunchedEffect(session.serverUrl, session.username, currentPath) {
        loading = true
        error = null
        try {
            items = withContext(Dispatchers.IO) {
                repository.listFolder(session, currentPath)
                    .sortedWith(compareBy({ !it.isDirectory }, { it.name.lowercase() }))
            }
        } catch (_: UnauthorizedException) {
            onUnauthorized()
        } catch (e: Exception) {
            error = e.message ?: "Не удалось загрузить файлы"
            items = emptyList()
        } finally {
            loading = false
        }
    }

    BackHandler(enabled = currentPath.isNotBlank()) {
        currentPath = parentPath(currentPath)
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(F7Colors.Surface),
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 12.dp, vertical = 12.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(8.dp),
        ) {
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .clip(CircleShape)
                    .clickable(onClick = {
                        if (currentPath.isBlank()) onCancel() else currentPath = parentPath(currentPath)
                    }),
                contentAlignment = Alignment.Center,
            ) {
                AsyncImage(
                    model = "$base/themes/forbion/images/mail/arrow-back-gray.svg",
                    contentDescription = "Назад",
                    modifier = Modifier.size(20.dp),
                    contentScale = ContentScale.Fit,
                )
            }
            Column(modifier = Modifier.weight(1f)) {
                Text(title, fontWeight = FontWeight.Bold, fontSize = 16.sp)
                Text(
                    if (currentPath.isBlank()) "Файлы" else currentPath,
                    style = MaterialTheme.typography.bodySmall,
                    color = F7Colors.TextSecondary,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                )
            }
        }
        when {
            loading -> Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center,
            ) {
                CircularProgressIndicator(color = F7Colors.Primary)
            }
            error != null -> Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center,
            ) {
                Text(error.orEmpty(), color = F7Colors.TextSecondary)
            }
            else -> LazyColumn(
                modifier = Modifier.fillMaxSize(),
            ) {
                items(items, key = { it.relativePath }) { item ->
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable {
                                if (item.isDirectory) {
                                    currentPath = item.relativePath
                                } else {
                                    onFileSelected(item)
                                }
                            }
                            .padding(horizontal = 16.dp, vertical = 12.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(12.dp),
                    ) {
                        AsyncImage(
                            model = if (item.isDirectory) {
                                "$base/themes/forbion/images/mail/folder-add-black.svg"
                            } else {
                                "$base/themes/forbion/images/mail/file-up-gray.svg"
                            },
                            contentDescription = null,
                            modifier = Modifier.size(20.dp),
                            contentScale = ContentScale.Fit,
                        )
                        Text(
                            item.name,
                            modifier = Modifier.weight(1f),
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis,
                        )
                    }
                }
            }
        }
    }
}

private fun parentPath(path: String): String {
    val trimmed = path.trim('/')
    if (trimmed.isBlank()) return ""
    val index = trimmed.lastIndexOf('/')
    return if (index < 0) "" else trimmed.substring(0, index)
}
