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 EOLAlertsScreen() {
  const [items, setItems] = useState<any[]>([])
  const [loading, setLoading] = useState(false)

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

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

  const createSR = async (item: any) => {
    try {
      await client.post('/api/tasks', { title: `EOL 조치: ${item.name} ${item.version ?? ''}`, description: `서버 ${item.server_count ?? '-'}대 영향 — EOL 소프트웨어 교체/업그레이드 필요`, priority: 'HIGH', sr_type: 'CHANGE' })
      Alert.alert('완료', 'SR이 등록됐습니다.')
    } catch { Alert.alert('오류', 'SR 등록에 실패했습니다.') }
  }

  return (
    <FlatList
      data={items}
      keyExtractor={(_, i) => String(i)}
      refreshControl={<RefreshControl refreshing={loading} onRefresh={load} />}
      ListEmptyComponent={<Text style={s.empty}>EOL 소프트웨어가 없습니다.</Text>}
      style={{ backgroundColor: COLORS.bg }}
      contentContainerStyle={{ padding: 12 }}
      renderItem={({ item }) => {
        const isEOL = !item.eol_date || new Date(item.eol_date) <= new Date()
        return (
          <View style={[s.card, { borderLeftWidth: 4, borderLeftColor: isEOL ? COLORS.danger : COLORS.warning }]}>
            <Text style={s.name}>{item.name} {item.version ?? ''}</Text>
            <Text style={s.meta}>EOL: {item.eol_date?.slice(0, 10) ?? '이미 만료'} · 서버 {item.server_count ?? 0}대</Text>
            <Text style={s.desc} numberOfLines={1}>{item.note ?? item.description ?? ''}</Text>
            <TouchableOpacity style={s.srBtn} onPress={() => createSR(item)}>
              <Text style={s.srText}>교체 SR 등록</Text>
            </TouchableOpacity>
          </View>
        )
      }}
    />
  )
}

const s = StyleSheet.create({
  card:   { backgroundColor: '#fff', borderRadius: 10, padding: 14, marginBottom: 8, elevation: 1 },
  name:   { fontSize: 14, fontWeight: '700', color: COLORS.text, marginBottom: 4 },
  meta:   { fontSize: 12, color: COLORS.muted, marginBottom: 4 },
  desc:   { fontSize: 12, color: COLORS.muted, marginBottom: 10 },
  srBtn:  { backgroundColor: COLORS.warning + '20', borderRadius: 6, padding: 8, alignItems: 'center' },
  srText: { color: COLORS.warning, fontSize: 12, fontWeight: '700' },
  empty:  { textAlign: 'center', color: COLORS.muted, marginTop: 40 },
})
