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

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

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

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

  const createSR = async (item: any) => {
    try {
      await client.post('/api/tasks', { title: `[예측 장애 예방] ${item.server_name ?? item.name}`, description: `장애 발생 가능성 ${item.probability ?? '-'}% — AI 예측 기반 예방 점검`, priority: 'HIGH', sr_type: 'INCIDENT' })
      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}>예측된 장애가 없습니다.</Text>}
      style={{ backgroundColor: COLORS.bg }}
      contentContainerStyle={{ padding: 12 }}
      renderItem={({ item }) => {
        const prob = item.probability ?? item.risk_score ?? 0
        const color = prob >= 70 ? COLORS.danger : prob >= 40 ? COLORS.warning : COLORS.success
        return (
          <View style={[s.card, { borderLeftWidth: 4, borderLeftColor: color }]}>
            <View style={s.row}>
              <View style={{ flex: 1 }}>
                <Text style={s.name}>{item.server_name ?? item.name}</Text>
                <Text style={s.meta}>{item.failure_type ?? item.type ?? '알 수 없음'} · {item.estimated_time ?? '72시간 이내'}</Text>
              </View>
              <Text style={[s.prob, { color }]}>{prob}%</Text>
            </View>
            <Text style={s.reason} numberOfLines={2}>{item.reason ?? item.description ?? ''}</Text>
            <Text style={s.action} onPress={() => createSR(item)}>예방 SR 등록 →</Text>
          </View>
        )
      }}
    />
  )
}

const s = StyleSheet.create({
  card:   { backgroundColor: '#fff', borderRadius: 10, padding: 14, marginBottom: 8, elevation: 1 },
  row:    { flexDirection: 'row', alignItems: 'center', marginBottom: 6 },
  name:   { fontSize: 14, fontWeight: '700', color: COLORS.text },
  meta:   { fontSize: 12, color: COLORS.muted, marginTop: 2 },
  prob:   { fontSize: 26, fontWeight: '800' },
  reason: { fontSize: 12, color: COLORS.muted, marginBottom: 8 },
  action: { color: COLORS.blue, fontSize: 13, fontWeight: '700' },
  empty:  { textAlign: 'center', color: COLORS.muted, marginTop: 40 },
})
