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

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

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

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

  const SEV_COLOR: Record<string, string> = { HIGH: COLORS.danger, MEDIUM: COLORS.warning, LOW: 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 }}
      ListHeaderComponent={<Text style={s.header}>정책 위반 경보 ({items.length}건)</Text>}
      renderItem={({ item }) => {
        const sev = item.severity ?? 'MEDIUM'
        const color = SEV_COLOR[sev] ?? COLORS.muted
        return (
          <View style={[s.card, { borderLeftWidth: 4, borderLeftColor: color }]}>
            <View style={s.row}>
              <View style={{ flex: 1 }}>
                <Text style={s.rule}>{item.policy_name ?? item.rule}</Text>
                <Text style={s.meta}>{item.resource ?? item.target} · {item.detected_at?.slice(0, 16) ?? ''}</Text>
              </View>
              <Text style={[s.sev, { color }]}>{sev}</Text>
            </View>
            <Text style={s.desc} numberOfLines={2}>{item.description ?? item.details ?? ''}</Text>
          </View>
        )
      }}
    />
  )
}

const s = StyleSheet.create({
  header: { fontSize: 16, fontWeight: '800', color: COLORS.text, marginBottom: 12 },
  card:   { backgroundColor: '#fff', borderRadius: 10, padding: 14, marginBottom: 8, elevation: 1 },
  row:    { flexDirection: 'row', alignItems: 'center', gap: 10, marginBottom: 6 },
  rule:   { fontSize: 13, fontWeight: '700', color: COLORS.text },
  meta:   { fontSize: 11, color: COLORS.muted, marginTop: 2 },
  sev:    { fontSize: 12, fontWeight: '700' },
  desc:   { fontSize: 12, color: COLORS.muted },
  empty:  { textAlign: 'center', color: COLORS.muted, marginTop: 40 },
})
