import React, { useState, useCallback } from 'react'
import { View, Text, FlatList, StyleSheet, RefreshControl, TouchableOpacity, Alert } from 'react-native'
import { useFocusEffect } from 'expo-router'
import { COLORS } from '../../constants/Config'
import client from '../../services/api'

export default function MaintenanceWindowScreen() {
  const [items, setItems] = useState<any[]>([])
  const [loading, setLoading] = useState(false)

  const load = useCallback(async () => {
    setLoading(true)
    try { const r = await client.get('/api/cmdb/maintenance'); setItems(r.data?.windows ?? r.data?.items ?? []) }
    catch { setItems([]) } finally { setLoading(false) }
  }, [])

  useFocusEffect(useCallback(() => { load() }, [load]))

  const cancel = (item: any) => {
    Alert.alert('취소 확인', `유지보수 창 "${item.title}"을 취소하시겠습니까?`, [
      { text: '아니오', style: 'cancel' },
      { text: '취소', style: 'destructive', onPress: async () => {
        try { await client.delete(`/api/cmdb/maintenance/${item.id}`); load() }
        catch { Alert.alert('오류', '취소에 실패했습니다.') }
      }},
    ])
  }

  const now = new Date()
  const statusOf = (item: any) => {
    const start = new Date(item.start_at ?? item.starts_at)
    const end   = new Date(item.end_at ?? item.ends_at)
    if (now < start) return { label: '예정', color: COLORS.blue }
    if (now <= end)  return { label: '진행중', color: COLORS.success }
    return { label: '완료', color: COLORS.muted }
  }

  return (
    <FlatList
      data={items}
      keyExtractor={(_, i) => String(i)}
      refreshControl={<RefreshControl refreshing={loading} onRefresh={load} />}
      ListEmptyComponent={<Text style={s.empty}>유지보수 일정이 없습니다.</Text>}
      style={{ backgroundColor: COLORS.bg }}
      contentContainerStyle={{ padding: 12 }}
      renderItem={({ item }) => {
        const st = statusOf(item)
        return (
          <View style={s.card}>
            <View style={s.header}>
              <Text style={s.title}>{item.title}</Text>
              <View style={[s.badge, { backgroundColor: st.color + '20' }]}>
                <Text style={[s.badgeText, { color: st.color }]}>{st.label}</Text>
              </View>
            </View>
            <Text style={s.time}>{item.start_at?.slice(0, 16) ?? '-'} ~ {item.end_at?.slice(0, 16) ?? '-'}</Text>
            <Text style={s.desc} numberOfLines={2}>{item.description ?? ''}</Text>
            {st.label === '예정' && (
              <TouchableOpacity style={s.cancelBtn} onPress={() => cancel(item)}>
                <Text style={s.cancelText}>일정 취소</Text>
              </TouchableOpacity>
            )}
          </View>
        )
      }}
    />
  )
}

const s = StyleSheet.create({
  card:       { backgroundColor: '#fff', borderRadius: 10, padding: 14, marginBottom: 8, elevation: 1 },
  header:     { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 },
  title:      { fontSize: 14, fontWeight: '700', color: COLORS.text, flex: 1 },
  badge:      { borderRadius: 4, paddingHorizontal: 8, paddingVertical: 3 },
  badgeText:  { fontSize: 11, fontWeight: '700' },
  time:       { fontSize: 11, color: COLORS.muted, marginBottom: 6 },
  desc:       { fontSize: 12, color: COLORS.muted, marginBottom: 10 },
  cancelBtn:  { backgroundColor: COLORS.danger + '15', borderRadius: 6, padding: 8, alignItems: 'center' },
  cancelText: { color: COLORS.danger, fontSize: 12, fontWeight: '700' },
  empty:      { textAlign: 'center', color: COLORS.muted, marginTop: 40 },
})
