package io.nexilis.alpha.ui.main

import android.Manifest
import android.content.pm.PackageManager
import android.net.Uri
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest
import io.nexilis.alpha.BuildConfig
import io.nexilis.alpha.ui.viewmodel.MainViewModel
import io.nexilis.service.core.createImageFile
import io.nexilis.service.data.viewmodels.BuddyViewModel
import java.util.Objects


@Composable
fun Profile(contentPadding: PaddingValues = PaddingValues(0.dp), mainViewModel: MainViewModel) {
    SideEffect {
        mainViewModel.setTitle("Profile")
    }
    val viewModel: BuddyViewModel = hiltViewModel()
    val me by viewModel.me.observeAsState()
    val context = LocalContext.current
    val file = context.createImageFile()
    val uri = FileProvider.getUriForFile(
        Objects.requireNonNull(context),
        BuildConfig.APPLICATION_ID + ".provider", file
    )
    var imageUri by remember { mutableStateOf<Uri>(Uri.EMPTY) }
    val launcher = rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) {
        if (it && uri.path?.isNotEmpty() == true) {
            me?.let { me ->
                viewModel.changeProfile(me.f_pin, file) {
                    imageUri = uri
                }
            }
        }
    }
    val permissionLauncher = rememberLauncherForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) {
        if (it) {
            Toast.makeText(context, "Permission Granted", Toast.LENGTH_SHORT).show()
            launcher.launch(uri)
        } else {
            Toast.makeText(context, "Permission Denied", Toast.LENGTH_SHORT).show()
        }
    }
    Column(
        modifier = Modifier
            .padding(contentPadding)
            .padding(start = 16.dp, end = 16.dp)
            .fillMaxWidth()
    ) {
        Box(
            Modifier.align(Alignment.CenterHorizontally),
            contentAlignment = Alignment.BottomEnd,
        ) {
            val painter: Painter =
                if (imageUri.path?.isNotEmpty() == true)
                    rememberAsyncImagePainter(imageUri)
                else rememberAsyncImagePainter(
                    model = ImageRequest.Builder(LocalContext.current)
                        .data("https://digixplatform.com/filepalio/image/${me?.image_id}")
                        .addHeader("Cookie", "PHPSESSID=123;MOBILE=123")
                        .crossfade(true)
                        .build()
                )
            Image(
                painter = painter, contentDescription = "", modifier = Modifier
                    .padding(top = 8.dp, end = 16.dp, bottom = 8.dp)
                    .clip(CircleShape)
                    .size(150.dp),
                contentScale = ContentScale.Crop
            )
            IconButton(onClick = {
                val permissionCheckResult =
                    ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
                if (permissionCheckResult == PackageManager.PERMISSION_GRANTED) {
                    launcher.launch(uri)
                } else {
                    permissionLauncher.launch(Manifest.permission.CAMERA)
                }
            }) {
                Icon(
                    imageVector = Icons.Default.AddCircle,
                    contentDescription = "",
                    tint = MaterialTheme.colorScheme.primary
                )
            }
        }
        Spacer(modifier = Modifier.size(16.dp))
        ListItem(
            headlineContent = { Text("Name", style = MaterialTheme.typography.bodySmall) },
            supportingContent = {
                me?.first_name?.let {
                    Text(
                        it,
                        style = MaterialTheme.typography.titleMedium
                    )
                }
            },
            leadingContent = {
                Icon(imageVector = Icons.Default.Person, contentDescription = "")
            }
        )
        ListItem(
            headlineContent = { Text("About", style = MaterialTheme.typography.bodySmall) },
            supportingContent = { Text("Yahoo", style = MaterialTheme.typography.titleMedium) },
            leadingContent = {
                Icon(imageVector = Icons.Default.Info, contentDescription = "")
            }
        )
        ListItem(
            headlineContent = { Text("Phone", style = MaterialTheme.typography.bodySmall) },
            supportingContent = {
                Text(
                    "08112345678",
                    style = MaterialTheme.typography.titleMedium
                )
            },
            leadingContent = {
                Icon(imageVector = Icons.Default.Call, contentDescription = "")
            }
        )
        ListItem(
            headlineContent = { Text("Email", style = MaterialTheme.typography.bodySmall) },
            supportingContent = {
                Text(
                    "yayandw@gmail.com",
                    style = MaterialTheme.typography.titleMedium
                )
            },
            leadingContent = {
                Icon(imageVector = Icons.Default.Email, contentDescription = "")
            }
        )
    }
}