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 AIHistoryScreen() {
  const [items, setItems]   = useState<any[]>([])
  const [page, setPage]     = useState(0)
  const [hasMore, setHasMore] = useState(true)
  const [loading, setLoading] = useState(false)

  const load = useCallback(async (p = 0) => {
    setLoading(true)
    try {
      const r = await client.get('/api/mobile2/chatbot-history', { params: { page: p, size: 20 } })
      const rows = r.data?.items ?? r.data ?? []
      setItems(prev => p === 0 ? rows : [...prev, ...rows])
      setHasMore(rows.length === 20)
      setPage(p)
    } catch { if (p === 0) setItems([]) } finally { setLoading(false) }
  }, [])

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

  const roleColor = (role: string) => role === 'user' ? COLORS.blue : COLORS.accent

  return (
    <FlatList
      data={items}
      keyExtractor={(_, i) => String(i)}
      refreshControl={<RefreshControl refreshing={loading && page === 0} onRefresh={() => load(0)} />}
      onEndReached={() => hasMore && !loading && load(page + 1)}
      onEndReachedThreshold={0.3}
      ListEmptyComponent={<Text style={s.empty}>AI 대화 이력이 없습니다.</Text>}
      style={{ backgroundColor: COLORS.bg }}
      contentContainerStyle={{ padding: 12 }}
      renderItem={({ item }) => (
        <View style={[s.bubble, { alignSelf: item.role === 'user' ? 'flex-end' : 'flex-start', backgroundColor: roleColor(item.role) + '15', borderColor: roleColor(item.role) + '40' }]}>
          <Text style={[s.role, { color: roleColor(item.role) }]}>{item.role === 'user' ? '나' : 'AI'}</Text>
          <Text style={s.content}>{item.content ?? item.message}</Text>
          <Text style={s.time}>{item.created_at?.slice(0, 16) ?? ''}</Text>
        </View>
      )}
    />
  )
}

const s = StyleSheet.create({
  bubble:  { maxWidth: '80%', borderWidth: 1, borderRadius: 12, padding: 12, marginBottom: 8 },
  role:    { fontSize: 11, fontWeight: '700', marginBottom: 4 },
  content: { fontSize: 13, color: COLORS.text, lineHeight: 20 },
  time:    { fontSize: 10, color: COLORS.muted, marginTop: 4, textAlign: 'right' },
  empty:   { textAlign: 'center', color: COLORS.muted, marginTop: 40 },
})
