package com.example.ops_android.ui.schedule

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowLeft
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.ops_android.ui.LocalAppContainer
import java.text.SimpleDateFormat
import java.util.*

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ScheduleScreen(
    onBack: () -> Unit
) {
    val vm: ScheduleViewModel = viewModel(factory = ScheduleViewModel.Factory(LocalAppContainer.current.scheduleRepository))
    val s by vm.uiState.collectAsState()
    val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US)

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("日程管理") },
                navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, null, tint = Color.White) } },
                actions = { IconButton(onClick = { vm.showAddForm(dateFormat.format(Date())) }) { Icon(Icons.Default.Add, "添加", tint = Color.White) } },
                colors = TopAppBarDefaults.topAppBarColors(containerColor = Color(0xFF667EEA), titleContentColor = Color.White)
            )
        }
    ) { padding ->
        LazyColumn(Modifier.fillMaxSize().padding(padding)) {
            // Month header
            item {
                Card(Modifier.fillMaxWidth().padding(12.dp)) {
                    Column(Modifier.padding(8.dp)) {
                        Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
                            IconButton(onClick = { vm.prevMonth() }) { Icon(Icons.AutoMirrored.Filled.KeyboardArrowLeft, "上月") }
                            Text("${s.currentYear}年 ${s.currentMonth + 1}月", fontWeight = FontWeight.Bold, fontSize = 18.sp)
                            IconButton(onClick = { vm.nextMonth() }) { Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, "下月") }
                        }

                        // Weekday headers
                        Row(Modifier.fillMaxWidth()) {
                            listOf("日", "一", "二", "三", "四", "五", "六").forEach { day ->
                                Text(day, Modifier.weight(1f), textAlign = TextAlign.Center, fontSize = 12.sp, color = Color.Gray)
                            }
                        }
                        Spacer(Modifier.height(4.dp))

                        // Calendar grid
                        val cal = Calendar.getInstance().apply { set(s.currentYear, s.currentMonth, 1) }
                        val firstDayOfWeek = cal.get(Calendar.DAY_OF_WEEK) - 1
                        val daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH)
                        val today = SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date())

                        var dayCount = 0
                        val weeks = mutableListOf<List<Int?>>()
                        var currentWeek = mutableListOf<Int?>()
                        for (i in 0 until firstDayOfWeek) { currentWeek.add(null); dayCount++ }
                        for (day in 1..daysInMonth) { currentWeek.add(day); dayCount++; if (dayCount % 7 == 0) { weeks.add(currentWeek.toList()); currentWeek = mutableListOf() } }
                        if (currentWeek.isNotEmpty()) { while (currentWeek.size < 7) currentWeek.add(null); weeks.add(currentWeek.toList()) }

                        weeks.forEach { week ->
                            Row(Modifier.fillMaxWidth()) {
                                week.forEach { day ->
                                    val cellModifier = Modifier.weight(1f).aspectRatio(1f).padding(2.dp)
                                    if (day != null) {
                                        val dateStr = String.format("%04d-%02d-%02d", s.currentYear, s.currentMonth + 1, day)
                                        val hasEvent = s.events.any { it.start_time?.startsWith(dateStr) == true }
                                        val isToday = dateStr == today

                                        Box(
                                            cellModifier.clip(CircleShape)
                                                .then(if (isToday) Modifier.background(Color(0xFF667EEA)) else Modifier)
                                                .clickable { vm.showAddForm(dateStr) },
                                            contentAlignment = Alignment.Center
                                        ) {
                                            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                                                Text(day.toString(), fontSize = 13.sp, color = if (isToday) Color.White else Color.Black)
                                                if (hasEvent) Box(Modifier.size(4.dp).clip(CircleShape).background(if (isToday) Color.White else Color(0xFF667EEA)))
                                            }
                                        }
                                    } else {
                                        Spacer(cellModifier)
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // Events list
            item { Text("日程列表", fontWeight = FontWeight.Bold, fontSize = 16.sp, modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) }

            if (s.events.isEmpty()) {
                item { Box(Modifier.fillMaxWidth().padding(32.dp), contentAlignment = Alignment.Center) { Text("暂无日程", color = Color.Gray) } }
            } else {
                items(s.events.sortedBy { it.start_time }) { event ->
                    Card(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp).clickable { vm.showEditForm(event) }) {
                        Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
                            Column(Modifier.weight(1f)) {
                                Text(event.title ?: "", fontWeight = FontWeight.Medium)
                                val timeStr = listOfNotNull(event.start_time?.substring(11)?.take(5), event.end_time?.substring(11)?.take(5)).joinToString(" ~ ")
                                if (timeStr.isNotBlank()) Text(timeStr, fontSize = 12.sp, color = Color.Gray)
                            }
                        }
                    }
                }
            }
        }
    }

    // Form dialog
    if (s.showForm) AlertDialog(
        onDismissRequest = { vm.dismissForm() },
        title = { Text(if (s.editingEvent != null) "编辑日程" else "添加日程") },
        text = {
            Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                OutlinedTextField(s.formTitle, vm::onFormTitle, label = { Text("标题 *") }, singleLine = true, modifier = Modifier.fillMaxWidth())
                OutlinedTextField(s.formDescription, vm::onFormDesc, label = { Text("描述") }, minLines = 2, modifier = Modifier.fillMaxWidth())
                Text("日期: ${s.formDate}", fontSize = 14.sp, color = Color.Gray)
                Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                    OutlinedTextField(s.formStartTime, vm::onFormStartTime, label = { Text("开始") }, placeholder = { Text("HH:mm") }, singleLine = true, modifier = Modifier.weight(1f))
                    OutlinedTextField(s.formEndTime, vm::onFormEndTime, label = { Text("结束") }, placeholder = { Text("HH:mm") }, singleLine = true, modifier = Modifier.weight(1f))
                }
            }
        },
        confirmButton = {
            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                if (s.editingEvent != null) {
                    TextButton(onClick = { vm.deleteEvent(s.editingEvent!!.id); vm.dismissForm() }) { Text("删除", color = Color.Red) }
                }
                Button(onClick = { vm.submitForm() }, enabled = !s.isSubmitting) { Text("保存") }
            }
        },
        dismissButton = { TextButton(onClick = { vm.dismissForm() }) { Text("取消") } }
    )
}
