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

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const [r, s] = await Promise.all([
        client.get('/api/compliance/csap/items'),
        client.get('/api/compliance/csap/dashboard'),
      ])
      setItems(r.data?.items ?? r.data ?? [])
      setSummary(s.data)
    } catch { setItems([]) } finally { setLoading(false) }
  }, [])

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

  const autoSR = async (item: any) => {
    try {
      await client.post('/api/tasks', { title: `CSAP 조치: ${item.control_id} ${item.title}`, description: item.remediation ?? item.description, priority: 'HIGH', sr_type: 'COMPLIANCE' })
      Alert.alert('완료', 'SR이 등록됐습니다.')
    } catch { Alert.alert('오류', 'SR 등록에 실패했습니다.') }
  }

  const failItems = items.filter(i => i.status === 'fail' || i.status === 'FAIL')
  const passCount = items.length - failItems.length
  const pct = items.length > 0 ? Math.round((passCount / items.length) * 100) : 0

  return (
    <FlatList
      data={failItems}
      keyExtractor={(_, i) => String(i)}
      refreshControl={<RefreshControl refreshing={loading} onRefresh={load} />}
      ListEmptyComponent={<Text style={s.empty}>{loading ? '' : '미준수 항목이 없습니다. CSAP 심사 준비 완료!'}</Text>}
      style={{ backgroundColor: COLORS.bg }}
      contentContainerStyle={{ padding: 12 }}
      ListHeaderComponent={
        <View style={s.header}>
          <View style={s.pctRow}>
            <Text style={s.pctNum}>{pct}%</Text>
            <Text style={s.pctLabel}>CSAP 준수율</Text>
          </View>
          <Text style={s.sub}>미준수 {failItems.length}건 / 전체 {items.length}건</Text>
        </View>
      }
      renderItem={({ item }) => (
        <View style={[s.card, { borderLeftWidth: 4, borderLeftColor: COLORS.danger }]}>
          <Text style={s.ctrlId}>{item.control_id} — {item.title ?? item.name}</Text>
          <Text style={s.desc} numberOfLines={2}>{item.description ?? ''}</Text>
          <TouchableOpacity style={s.btn} onPress={() => autoSR(item)}>
            <Text style={s.btnText}>자동 SR 등록</Text>
          </TouchableOpacity>
        </View>
      )}
    />
  )
}

const s = StyleSheet.create({
  header:  { backgroundColor: '#fff', borderRadius: 12, padding: 16, marginBottom: 12, alignItems: 'center', elevation: 2 },
  pctRow:  { flexDirection: 'row', alignItems: 'baseline', gap: 8 },
  pctNum:  { fontSize: 52, fontWeight: '900', color: COLORS.accent },
  pctLabel:{ fontSize: 14, color: COLORS.muted },
  sub:     { fontSize: 12, color: COLORS.muted, marginTop: 4 },
  card:    { backgroundColor: '#fff', borderRadius: 10, padding: 14, marginBottom: 8, elevation: 1 },
  ctrlId:  { fontSize: 13, fontWeight: '700', color: COLORS.text, marginBottom: 4 },
  desc:    { fontSize: 12, color: COLORS.muted, marginBottom: 10 },
  btn:     { backgroundColor: COLORS.danger + '15', borderRadius: 6, padding: 8, alignItems: 'center' },
  btnText: { color: COLORS.danger, fontSize: 12, fontWeight: '700' },
  empty:   { textAlign: 'center', color: COLORS.success, marginTop: 40, fontSize: 14, fontWeight: '700' },
})
