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

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

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

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

  const urgency = (days: number) => days <= 7 ? COLORS.danger : days <= 30 ? COLORS.warning : COLORS.success

  return (
    <FlatList
      data={items.sort((a, b) => (a.days_left ?? 999) - (b.days_left ?? 999))}
      keyExtractor={(_, i) => String(i)}
      refreshControl={<RefreshControl refreshing={loading} onRefresh={load} />}
      ListEmptyComponent={<Text style={s.empty}>SSL 인증서 데이터가 없습니다.</Text>}
      style={{ backgroundColor: COLORS.bg }}
      contentContainerStyle={{ padding: 12 }}
      renderItem={({ item }) => {
        const days = item.days_left ?? item.days_remaining ?? 999
        const color = urgency(days)
        return (
          <View style={[s.card, { borderLeftWidth: 4, borderLeftColor: color }]}>
            <View style={s.row}>
              <View style={{ flex: 1 }}>
                <Text style={s.domain}>{item.domain ?? item.name}</Text>
                <Text style={s.meta}>만료: {item.expires_at?.slice(0, 10) ?? '-'} · 발급: {item.issuer ?? '-'}</Text>
              </View>
              <View style={[s.daysBadge, { backgroundColor: color }]}>
                <Text style={s.daysNum}>{days}</Text>
                <Text style={s.daysLabel}>일 남음</Text>
              </View>
            </View>
          </View>
        )
      }}
    />
  )
}

const s = StyleSheet.create({
  card:      { backgroundColor: '#fff', borderRadius: 10, padding: 14, marginBottom: 8, elevation: 1 },
  row:       { flexDirection: 'row', alignItems: 'center', gap: 12 },
  domain:    { fontSize: 14, fontWeight: '700', color: COLORS.text },
  meta:      { fontSize: 11, color: COLORS.muted, marginTop: 3 },
  daysBadge: { alignItems: 'center', borderRadius: 8, paddingVertical: 6, paddingHorizontal: 10 },
  daysNum:   { fontSize: 20, fontWeight: '900', color: '#fff' },
  daysLabel: { fontSize: 9, color: '#fff', fontWeight: '600' },
  empty:     { textAlign: 'center', color: COLORS.muted, marginTop: 40 },
})
