package com.rosetta.messenger.ui.chats.attach

import android.content.ContentUris
import android.content.Context
import android.provider.MediaStore
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

private const val TAG = "MediaRepository"

/**
 * Loads media items from device gallery, grouped into albums.
 * Mirrors Telegram's MediaController album loading logic:
 * - "All media" album (bucketId=0) contains everything sorted by date
 * - Real albums sorted: All media first, then by item count descending
 */
suspend fun loadMediaPickerData(context: Context): MediaPickerData = withContext(Dispatchers.IO) {
    val items = mutableListOf<MediaItem>()

    try {
        // Query images with bucket info
        val imageProjection = arrayOf(
            MediaStore.Images.Media._ID,
            MediaStore.Images.Media.MIME_TYPE,
            MediaStore.Images.Media.DATE_MODIFIED,
            MediaStore.Images.Media.BUCKET_ID,
            MediaStore.Images.Media.BUCKET_DISPLAY_NAME
        )

        context.contentResolver.query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            imageProjection,
            null,
            null,
            "${MediaStore.Images.Media.DATE_MODIFIED} DESC"
        )?.use { cursor ->
            val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
            val mimeColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.MIME_TYPE)
            val dateColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_MODIFIED)
            val bucketIdColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_ID)
            val bucketNameColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME)

            while (cursor.moveToNext()) {
                val id = cursor.getLong(idColumn)
                val mimeType = cursor.getString(mimeColumn) ?: "image/*"
                val dateModified = cursor.getLong(dateColumn)
                val bucketId = cursor.getLong(bucketIdColumn)
                val bucketName = cursor.getString(bucketNameColumn) ?: "Unknown"

                val uri = ContentUris.withAppendedId(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    id
                )

                items.add(
                    MediaItem(
                        id = id,
                        uri = uri,
                        mimeType = mimeType,
                        dateModified = dateModified,
                        bucketId = bucketId,
                        bucketName = bucketName
                    )
                )
            }
        }

        // Query videos with bucket info
        val videoProjection = arrayOf(
            MediaStore.Video.Media._ID,
            MediaStore.Video.Media.MIME_TYPE,
            MediaStore.Video.Media.DURATION,
            MediaStore.Video.Media.DATE_MODIFIED,
            MediaStore.Video.Media.BUCKET_ID,
            MediaStore.Video.Media.BUCKET_DISPLAY_NAME
        )

        context.contentResolver.query(
            MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
            videoProjection,
            null,
            null,
            "${MediaStore.Video.Media.DATE_MODIFIED} DESC"
        )?.use { cursor ->
            val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID)
            val mimeColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE)
            val durationColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION)
            val dateColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_MODIFIED)
            val bucketIdColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.BUCKET_ID)
            val bucketNameColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.BUCKET_DISPLAY_NAME)

            while (cursor.moveToNext()) {
                val id = cursor.getLong(idColumn)
                val mimeType = cursor.getString(mimeColumn) ?: "video/*"
                val duration = cursor.getLong(durationColumn)
                val dateModified = cursor.getLong(dateColumn)
                val bucketId = cursor.getLong(bucketIdColumn)
                val bucketName = cursor.getString(bucketNameColumn) ?: "Unknown"

                val uri = ContentUris.withAppendedId(
                    MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                    id
                )

                // Use negative id to avoid collision with images
                items.add(
                    MediaItem(
                        id = -id,
                        uri = uri,
                        mimeType = mimeType,
                        duration = duration,
                        dateModified = dateModified,
                        bucketId = bucketId,
                        bucketName = bucketName
                    )
                )
            }
        }

        // Sort all items by date
        items.sortByDescending { it.dateModified }
    } catch (e: Exception) {
        Log.e(TAG, "Failed to load media", e)
    }

    // Build albums (like Telegram's updateAlbumsDropDown)
    val allMediaAlbum = MediaAlbum(
        id = ALL_MEDIA_ALBUM_ID,
        name = "All media",
        items = items,
        isAllMedia = true
    )

    val bucketAlbums = items
        .groupBy { it.bucketId }
        .map { (bucketId, bucketItems) ->
            MediaAlbum(
                id = bucketId,
                name = bucketItems.first().bucketName,
                items = bucketItems.sortedByDescending { it.dateModified }
            )
        }
        .sortedByDescending { it.items.size } // Largest albums first, like Telegram

    val albums = listOf(allMediaAlbum) + bucketAlbums

    MediaPickerData(items = items, albums = albums)
}
