// Copyright (c) 2025 Gleb Zaharov. License: GPLv3 (see LICENSE).

package ru.sweetbread.unn.ui.composes

import android.util.Log
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.Canvas
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.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
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.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.zIndex
import com.kizitonwose.calendar.compose.weekcalendar.rememberWeekCalendarState
import com.kizitonwose.calendar.core.WeekDay
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import ru.sweetbread.unn.R
import ru.sweetbread.unn.api.Auditorium
import ru.sweetbread.unn.api.Building
import ru.sweetbread.unn.api.Discipline
import ru.sweetbread.unn.api.KindOfWork
import ru.sweetbread.unn.api.Lecturer
import ru.sweetbread.unn.api.LecturerRank
import ru.sweetbread.unn.api.ScheduleUnit
import ru.sweetbread.unn.api.getScheduleDay
import ru.sweetbread.unn.ui.theme.UNNTheme
import splitties.resources.appStr
import splitties.resources.appStrArray
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Calendar

@Composable
fun Schedule() {
    var selectedDate by remember { mutableStateOf(LocalDate.now()) }
    val calendarState = rememberWeekCalendarState(
        startDate = LocalDate.now(),
        firstVisibleWeekDate = LocalDate.now(),
        firstDayOfWeek = DayOfWeek.MONDAY
    )

    Column {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 8.dp),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            calendarState.firstVisibleWeek.days
                .filter { it.date.dayOfWeek != DayOfWeek.SUNDAY }
                .forEach { day ->
                    DayItem (
                        Modifier
                            .weight(1f)
                            .aspectRatio(1f)
                            .padding(2.dp),
                        day = day,
                        isSelected = day.date == selectedDate,
                        onClick = { selectedDate = day.date }
                    )
                }
        }

        ScheduleDay(date = selectedDate)
    }
}

@Composable
private fun DayItem(
    modifier: Modifier = Modifier,
    day: WeekDay,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    val isToday = day.date == LocalDate.now()

    Box(
        modifier = modifier
            .background(
                color = if (isSelected) MaterialTheme.colorScheme.inversePrimary
                else MaterialTheme.colorScheme.surfaceContainer,
                shape = if (isToday) CircleShape else RectangleShape
            )
            .clickable(
                onClick = onClick,
                enabled = !isSelected
            ),
        contentAlignment = Alignment.Center
    ) {
        Column (
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(
                text = day.date.dayOfMonth.toString(),
                fontWeight = if (isToday) FontWeight.Bold else null,
                color = MaterialTheme.colorScheme.onSurface
            )
            Text(
                text = appStrArray(R.array.short_weekdays)[day.date.dayOfWeek.value-1],
                fontWeight = if (isToday) FontWeight.Bold else null,
                color = MaterialTheme.colorScheme.onSurface
            )
        }
    }
}

@Composable
fun ScheduleDay(modifier: Modifier = Modifier, date: LocalDate) {
    val scope = rememberCoroutineScope()
    var loadedDate by remember { mutableStateOf(LocalDate.MIN) }
    val lessons = remember { mutableListOf<ScheduleUnit>() }
    var expanded by remember { mutableIntStateOf(0) }

    if (loadedDate == date) {
        Log.d("Loaded", "${date.format(DateTimeFormatter.ISO_DATE)} ${lessons.size}")
        LazyColumn (modifier) {
            items(lessons) {
                ScheduleItem(unit = it, modifier = Modifier.clickable {
                    expanded = if (it.oid == expanded) 0
                    else it.oid
                }, expanded = expanded == it.oid)
            }

            if (lessons.isEmpty())
                item { Text(appStr(R.string.noData)) }
        }
    } else {
        LinearProgressIndicator(
            modifier = Modifier
                .fillMaxWidth()
                .padding(8.dp),
            color = MaterialTheme.colorScheme.surfaceVariant,
            trackColor = MaterialTheme.colorScheme.secondary,
        )
        LaunchedEffect(date != loadedDate) {
            scope.launch(Dispatchers.IO) {
                lessons.clear()
                lessons.addAll(getScheduleDay(date = date))
                loadedDate = date
            }
        }
    }
}

@Composable
fun ScheduleItem(modifier: Modifier = Modifier, unit: ScheduleUnit, expanded: Boolean = false) {
    fun getRatio(): Float {
        val begin = LocalDateTime.of(unit.date, unit.begin).atZone(ZoneId.of("Europe/Moscow")).toEpochSecond()
        val end = LocalDateTime.of(unit.date, unit.end).atZone(ZoneId.of("Europe/Moscow")).toEpochSecond()
        val now =  LocalDateTime.now().atZone(ZoneId.of("Europe/Moscow")).toEpochSecond()
        if (begin > now)
            return -1f
        if (now > end)
            return 1f
        return (now - begin) / (end - begin).toFloat()
    }

    val begin = unit.begin.format(DateTimeFormatter.ofPattern("HH:mm"))
    val end = unit.end.format(DateTimeFormatter.ofPattern("HH:mm"))
    var ratio by remember { mutableFloatStateOf(getRatio()) }

    LaunchedEffect(Unit) {
        while (true) {
            val now = System.currentTimeMillis()
            val calendar = Calendar.getInstance().apply { timeInMillis = now }
            val seconds = calendar.get(Calendar.SECOND)
            val millisUntilNextMinute = (60 - seconds) * 1000L - calendar.get(Calendar.MILLISECOND)

            delay(millisUntilNextMinute)
            ratio = getRatio()
        }
    }

    val backgroundColor by animateColorAsState(
        targetValue = if (ratio == 1f)
            MaterialTheme.colorScheme.surfaceContainer
        else if (ratio == -1f)
            MaterialTheme.colorScheme.secondaryContainer
        else
            MaterialTheme.colorScheme.primaryContainer,
        label = "backgroundTransition"
    )

    Row (
        modifier
            .fillMaxWidth()
            .padding(4.dp)
            .clip(RoundedCornerShape(8.dp))
            .background(backgroundColor)
            .padding(8.dp)
    ){
        Column (Modifier.weight(1f)) {
            Column {
                Text(
                    text = unit.discipline.name,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.zIndex(1f),
                    maxLines = if (expanded) Int.MAX_VALUE else 1,
                    overflow = TextOverflow.Ellipsis
                )
            }

            AnimatedVisibility (expanded) {
                HorizontalDivider(
                    modifier = Modifier.padding(vertical = 16.dp),
                    thickness = 1.dp,
                    color = MaterialTheme.colorScheme.onBackground
                )
            }

            Column {
                Text(
                    text = unit.kindOfWork.name,
                    overflow = TextOverflow.Ellipsis
                )
                AnimatedVisibility (expanded) {
                    Text(text = unit.stream)
                }
            }

            AnimatedVisibility (expanded) {
                HorizontalDivider(
                    modifier = Modifier.padding(vertical = 16.dp),
                    thickness = 1.dp,
                    color = MaterialTheme.colorScheme.onBackground
                )
            }

            AnimatedVisibility (!expanded) {
                Row(Modifier) {
                    Text(
                        text = unit.auditorium.name,
                        fontWeight = FontWeight.Bold,
                        modifier = Modifier.padding(end = 4.dp)
                    )
                    Text(
                        text = unit.auditorium.building.name,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                }
            }
            AnimatedVisibility (expanded) {
                Column {
                    Text(
                        text = "${stringResource(R.string.auditorium)}: ${unit.auditorium.name}",
                        fontWeight = FontWeight.Bold,
                        modifier = Modifier.padding(end = 4.dp)
                    )
                    Text(
                        text = "${stringResource(R.string.building)}: ${unit.auditorium.building.name}",
                        overflow = TextOverflow.Ellipsis
                    )
                    if (unit.auditorium.floor != 0) {
                        Text(
                            text = "${stringResource(R.string.floor)}: ${unit.auditorium.floor}",
                            overflow = TextOverflow.Ellipsis
                        )
                    }

                    HorizontalDivider(
                        modifier = Modifier.padding(vertical = 16.dp),
                        thickness = 1.dp,
                        color = MaterialTheme.colorScheme.onBackground
                    )

                    Column {
                        Text(text = unit.lecturers[0].name, fontWeight = FontWeight.Bold)
                        Text(text = stringResource(unit.lecturers[0].rank.id))
                    }

                    HorizontalDivider(
                        modifier = Modifier.padding(vertical = 16.dp),
                        thickness = 1.dp,
                        color = MaterialTheme.colorScheme.onBackground
                    )

                    Row (Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically) {
                        Text(begin.toString(), fontWeight = FontWeight.Bold)
                        AnimatedVisibility (
                            (0f <= ratio) and (ratio < 1f),
                            modifier = Modifier
                                .weight(1f)
                                .padding(horizontal = 2.dp)
                        ) {
                            DividerWithMarker(
                                positionPercentage = ratio,
                                color = MaterialTheme.colorScheme.outline,
                                thickness = 3.dp,
                                markerSize = 8.dp,
                                markerColor = MaterialTheme.colorScheme.primary
                            )
                        }
                        Text(end.toString())
                    }
                }
            }
        }

        AnimatedVisibility (!expanded) {
            Column {
                Text(begin.toString(), fontWeight = FontWeight.Bold)
                Text(end.toString())
            }
        }
    }
}


@Composable
fun DividerWithMarker(
    modifier: Modifier = Modifier,
    positionPercentage: Float,
    color: Color = Color.Gray,
    thickness: Dp = 1.dp,
    markerSize: Dp = 8.dp,
    markerColor: Color = Color.Red
) {
    Canvas(modifier = modifier.height(thickness)) {
        val dividerHeight = thickness.toPx()
        val width = size.width
        val markerX = width * positionPercentage

        drawLine(
            color = markerColor,
            start = Offset(0f, dividerHeight / 2),
            end = Offset(markerX, dividerHeight / 2),
            strokeWidth = dividerHeight
        )

        drawLine(
            color = color,
            start = Offset(markerX, dividerHeight / 2),
            end = Offset(width, dividerHeight / 2),
            strokeWidth = dividerHeight / 2
        )

        drawCircle(
            color = markerColor,
            radius = markerSize.toPx() / 2,
            center = Offset(markerX, dividerHeight / 2)
        )
    }
}

@Preview
@Composable
fun ScheduleItemPreview() {
    val unit = ScheduleUnit(
        oid = 1,
        Auditorium(
            name = "с/з 1(110)",
            oid = 3752,
            floor = 0,
            building = Building(
                name = "Корпус 6",
                gid = 30,
                oid = 155
            ),
        ),
        date = LocalDate.of(2024, 3, 11),
        discipline = Discipline(
            name = "Физическая культура и спорт (элективная дисциплина)",
            oid = 67895,
            type = 0
        ),
        kindOfWork = KindOfWork(
            name = "Практика (семинарские занятия)",
            oid = 261,
            uid = "281474976710661",
            complexity = 1
        ),
        lecturers = arrayListOf(
            Lecturer(
                name = "Фамилия Имя Отчество",
                rank = LecturerRank.SLecturer,
                email = "",
                unnId = 28000,
                uid = "51000"
            )
        ),
        stream = "3823Б1ПР1|3823Б1ПР2|3823Б1ПР3|3823Б1ПР4|3823Б1ПР5-В-OUP",
        begin = LocalTime.of(10, 50),
        end = LocalTime.of(12, 20)
    )

    UNNTheme {
        Surface(color = MaterialTheme.colorScheme.background) {
            ScheduleItem(unit = unit)
        }
    }
}

@Preview
@Composable
fun ScheduleExpandedItemPreview() {
    val unit = ScheduleUnit(
        oid = 1,
        Auditorium(
            name = "с/з 1(110)",
            oid = 3752,
            floor = 0,
            building = Building(
                name = "Корпус 6",
                gid = 30,
                oid = 155
            ),
        ),
        date = LocalDate.of(2024, 3, 11),
        discipline = Discipline(
            name = "Физическая культура и спорт (элективная дисциплина)",
            oid = 67895,
            type = 0
        ),
        kindOfWork = KindOfWork(
            name = "Практика (семинарские занятия)",
            oid = 261,
            uid = "281474976710661",
            complexity = 1
        ),
        lecturers = arrayListOf(
            Lecturer(
                name = "Фамилия Имя Отчество",
                rank = LecturerRank.SLecturer,
                email = "",
                unnId = 28000,
                uid = "51000"
            )
        ),
        stream = "3823Б1ПР1|3823Б1ПР2|3823Б1ПР3|3823Б1ПР4|3823Б1ПР5-В-OUP",
        begin = LocalTime.of(10, 50),
        end = LocalTime.of(12, 20)
    )

    UNNTheme {
        Surface(color = MaterialTheme.colorScheme.background) {
            ScheduleItem(unit = unit, expanded = true)
        }
    }
}