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

export default function AIBriefingScreen() {
  const [data, setData]   = useState<any>(null)
  const [loading, setLoading] = useState(false)

  const load = useCallback(async () => {
    setLoading(true)
    try { const r = await client.get('/api/ai-insights/briefing'); setData(r.data) }
    catch { setData(null) } finally { setLoading(false) }
  }, [])

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

  if (loading) return <ActivityIndicator style={{ flex: 1 }} color={COLORS.accent} />
  if (!data)   return <Text style={s.empty}>브리핑을 불러올 수 없습니다.</Text>

  return (
    <ScrollView style={s.container} refreshControl={<RefreshControl refreshing={loading} onRefresh={load} />} contentContainerStyle={{ padding: 16 }}>
      <View style={s.header}>
        <Text style={s.title}>AI 주간 운영 브리핑</Text>
        <Text style={s.period}>{data.period ?? ''}</Text>
      </View>

      <View style={s.card}>
        <Text style={s.sectionTitle}>핵심 요약</Text>
        <Text style={s.body}>{data.summary ?? data.content ?? '데이터 없음'}</Text>
      </View>

      {data.highlights?.map((h: string, i: number) => (
        <View key={i} style={s.bulletRow}>
          <Text style={s.bullet}>•</Text>
          <Text style={s.bulletText}>{h}</Text>
        </View>
      ))}

      {data.risks?.length > 0 && (
        <View style={[s.card, { borderLeftWidth: 4, borderLeftColor: COLORS.danger }]}>
          <Text style={s.sectionTitle}>리스크</Text>
          {data.risks.map((r: string, i: number) => (
            <Text key={i} style={[s.bulletText, { color: COLORS.danger }]}>• {r}</Text>
          ))}
        </View>
      )}

      {data.recommendations?.length > 0 && (
        <View style={[s.card, { borderLeftWidth: 4, borderLeftColor: COLORS.success }]}>
          <Text style={s.sectionTitle}>AI 권고 사항</Text>
          {data.recommendations.map((r: string, i: number) => (
            <Text key={i} style={[s.bulletText, { color: COLORS.text }]}>• {r}</Text>
          ))}
        </View>
      )}
    </ScrollView>
  )
}

const s = StyleSheet.create({
  container:    { flex: 1, backgroundColor: COLORS.bg },
  empty:        { textAlign: 'center', color: COLORS.muted, marginTop: 40 },
  header:       { marginBottom: 16 },
  title:        { fontSize: 22, fontWeight: '800', color: COLORS.text },
  period:       { fontSize: 13, color: COLORS.muted, marginTop: 4 },
  card:         { backgroundColor: '#fff', borderRadius: 12, padding: 16, marginBottom: 12, elevation: 1 },
  sectionTitle: { fontSize: 14, fontWeight: '700', color: COLORS.text, marginBottom: 10 },
  body:         { fontSize: 14, color: COLORS.text, lineHeight: 22 },
  bulletRow:    { flexDirection: 'row', gap: 8, marginBottom: 6 },
  bullet:       { fontSize: 16, color: COLORS.accent, lineHeight: 22 },
  bulletText:   { flex: 1, fontSize: 13, color: COLORS.text, lineHeight: 20 },
})
