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 OllamaStatusScreen() {
  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/ollama-status'); setData(r.data) }
    catch { setData(null) } finally { setLoading(false) }
  }, [])

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

  const pull = async (model: string) => {
    Alert.alert('모델 Pull', `${model} 모델을 당겨오시겠습니까?`, [
      { text: '취소', style: 'cancel' },
      { text: '실행', onPress: async () => {
        try { await client.post('/api/ai-insights/ollama-pull', { model }); Alert.alert('완료', 'Pull 요청이 전송됐습니다.') }
        catch { Alert.alert('오류', '요청에 실패했습니다.') }
      }},
    ])
  }

  const models: any[] = data?.models ?? []
  const status = data?.status ?? 'unknown'
  const statusColor = status === 'running' ? COLORS.success : COLORS.danger

  return (
    <FlatList
      data={models}
      keyExtractor={(_, i) => String(i)}
      refreshControl={<RefreshControl refreshing={loading} onRefresh={load} />}
      ListEmptyComponent={<Text style={s.empty}>Ollama 데이터가 없습니다.</Text>}
      style={{ backgroundColor: COLORS.bg }}
      contentContainerStyle={{ padding: 12 }}
      ListHeaderComponent={
        <View style={s.statusCard}>
          <View style={[s.statusDot, { backgroundColor: statusColor }]} />
          <View style={{ flex: 1 }}>
            <Text style={s.statusLabel}>Ollama 서버 상태</Text>
            <Text style={[s.statusText, { color: statusColor }]}>{status.toUpperCase()}</Text>
          </View>
          <Text style={s.version}>{data?.version ?? ''}</Text>
        </View>
      }
      renderItem={({ item }) => (
        <View style={s.card}>
          <View style={s.row}>
            <View style={{ flex: 1 }}>
              <Text style={s.name}>{item.name}</Text>
              <Text style={s.meta}>{item.size ?? '-'} · 수정: {item.modified_at?.slice(0, 10) ?? '-'}</Text>
            </View>
            <TouchableOpacity style={s.pullBtn} onPress={() => pull(item.name)}>
              <Text style={s.pullText}>Pull</Text>
            </TouchableOpacity>
          </View>
        </View>
      )}
    />
  )
}

const s = StyleSheet.create({
  statusCard:  { backgroundColor: '#fff', borderRadius: 12, padding: 14, marginBottom: 12, flexDirection: 'row', alignItems: 'center', gap: 12, elevation: 2 },
  statusDot:   { width: 12, height: 12, borderRadius: 6 },
  statusLabel: { fontSize: 11, color: COLORS.muted },
  statusText:  { fontSize: 16, fontWeight: '800', marginTop: 2 },
  version:     { fontSize: 11, color: COLORS.muted },
  card:        { backgroundColor: '#fff', borderRadius: 10, padding: 14, marginBottom: 6, elevation: 1 },
  row:         { flexDirection: 'row', alignItems: 'center', gap: 10 },
  name:        { fontSize: 14, fontWeight: '700', color: COLORS.text },
  meta:        { fontSize: 11, color: COLORS.muted, marginTop: 3 },
  pullBtn:     { backgroundColor: COLORS.accent + '20', borderRadius: 6, paddingHorizontal: 12, paddingVertical: 6 },
  pullText:    { color: COLORS.accent, fontSize: 12, fontWeight: '700' },
  empty:       { textAlign: 'center', color: COLORS.muted, marginTop: 40 },
})
