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'

const SEV_COLOR: Record<string, string> = { CRITICAL: '#dc2626', HIGH: '#f97316', MEDIUM: COLORS.warning, LOW: COLORS.muted, NONE: '#94a3b8' }

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

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

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

  const applyPatch = async (item: any) => {
    Alert.alert('패치 적용', `${item.cve_id}를 대상 서버에 적용하시겠습니까?`, [
      { text: '취소', style: 'cancel' },
      { text: '적용', style: 'destructive', onPress: async () => {
        try {
          await client.post(`/api/patches/${item.cve_id}/apply`)
          Alert.alert('완료', '패치 적용 SR이 생성됐습니다.')
          load()
        } catch { Alert.alert('오류', '패치 적용에 실패했습니다.') }
      }},
    ])
  }

  return (
    <FlatList
      data={items}
      keyExtractor={(_, i) => String(i)}
      refreshControl={<RefreshControl refreshing={loading} onRefresh={load} />}
      ListEmptyComponent={<Text style={s.empty}>CVE 항목이 없습니다.</Text>}
      style={{ backgroundColor: COLORS.bg }}
      contentContainerStyle={{ padding: 12 }}
      renderItem={({ item }) => {
        const sev = item.severity ?? 'MEDIUM'
        const color = SEV_COLOR[sev] ?? COLORS.muted
        const cvss = item.cvss_score ?? item.score ?? 0
        return (
          <View style={s.card}>
            <View style={s.header}>
              <Text style={[s.cveId, { color }]}>{item.cve_id ?? item.id}</Text>
              <View style={[s.sevBadge, { backgroundColor: color }]}>
                <Text style={s.sevText}>{sev}</Text>
              </View>
            </View>
            <View style={s.cvssRow}>
              <Text style={s.cvssLabel}>CVSS</Text>
              <View style={s.cvssBar}>
                <View style={[s.cvssFill, { width: `${(cvss / 10) * 100}%`, backgroundColor: color }]} />
              </View>
              <Text style={[s.cvssScore, { color }]}>{Number(cvss).toFixed(1)}</Text>
            </View>
            <Text style={s.desc} numberOfLines={2}>{item.description ?? item.summary ?? ''}</Text>
            <View style={s.meta}>
              <Text style={s.metaText}>영향 서버: {item.affected_count ?? item.servers?.length ?? 0}개</Text>
              <Text style={s.metaText}>공개일: {item.published_at?.slice(0, 10) ?? '-'}</Text>
            </View>
            {item.status !== 'PATCHED' && (
              <TouchableOpacity style={s.patchBtn} onPress={() => applyPatch(item)}>
                <Text style={s.patchText}>패치 적용</Text>
              </TouchableOpacity>
            )}
            {item.status === 'PATCHED' && <Text style={[s.patched]}>패치 완료</Text>}
          </View>
        )
      }}
    />
  )
}

const s = StyleSheet.create({
  card:       { backgroundColor: '#fff', borderRadius: 12, padding: 14, marginBottom: 8, elevation: 1 },
  header:     { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 },
  cveId:      { fontSize: 14, fontWeight: '800' },
  sevBadge:   { paddingHorizontal: 8, paddingVertical: 3, borderRadius: 4 },
  sevText:    { color: '#fff', fontSize: 10, fontWeight: '700' },
  cvssRow:    { flexDirection: 'row', alignItems: 'center', gap: 8, marginBottom: 8 },
  cvssLabel:  { fontSize: 11, color: COLORS.muted, width: 36 },
  cvssBar:    { flex: 1, height: 6, backgroundColor: COLORS.border, borderRadius: 3, overflow: 'hidden' },
  cvssFill:   { height: '100%', borderRadius: 3 },
  cvssScore:  { fontSize: 14, fontWeight: '700', width: 28 },
  desc:       { fontSize: 12, color: COLORS.muted, marginBottom: 8, lineHeight: 18 },
  meta:       { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 10 },
  metaText:   { fontSize: 11, color: COLORS.muted },
  patchBtn:   { backgroundColor: COLORS.danger, borderRadius: 8, padding: 10, alignItems: 'center' },
  patchText:  { color: '#fff', fontSize: 13, fontWeight: '700' },
  patched:    { color: COLORS.success, fontSize: 13, fontWeight: '700', textAlign: 'center' },
  empty:      { textAlign: 'center', color: COLORS.muted, marginTop: 40 },
})
