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

export default function AutomationRulesScreen() {
  const [rules, setRules] = useState<any[]>([])
  const [loading, setLoading] = useState(false)

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const r = await getAutomationRules()
      setRules(r.data?.items ?? r.data ?? [])
    } catch { setRules([]) }
    finally { setLoading(false) }
  }, [])

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

  const renderItem = ({ item }: { item: any }) => (
    <View style={s.card}>
      <View style={s.row}>
        <View style={{ flex: 1 }}>
          <Text style={s.title}>{item.name ?? item.rule_name ?? '규칙'}</Text>
          <Text style={s.meta}>트리거: {item.trigger ?? item.condition ?? '-'}</Text>
          <Text style={s.meta}>액션: {item.action ?? item.action_type ?? '-'}</Text>
        </View>
        <View style={s.statusCol}>
          <Switch
            value={item.enabled ?? item.is_active ?? false}
            disabled
            trackColor={{ true: COLORS.accent, false: COLORS.border }}
          />
          <Text style={[s.badge, { backgroundColor: item.enabled ? COLORS.success : COLORS.muted }]}>
            {item.enabled ? '활성' : '비활성'}
          </Text>
        </View>
      </View>
    </View>
  )

  return (
    <View style={s.container}>
      <View style={s.notice}>
        <Text style={s.noticeText}>자동화 규칙 조회 전용 — 편집은 ITSM 웹에서 가능합니다.</Text>
      </View>
      <FlatList
        data={rules}
        keyExtractor={(_, i) => String(i)}
        renderItem={renderItem}
        refreshControl={<RefreshControl refreshing={loading} onRefresh={load} />}
        ListEmptyComponent={<Text style={s.empty}>자동화 규칙이 없습니다.</Text>}
        contentContainerStyle={{ padding: 12 }}
      />
    </View>
  )
}

const s = StyleSheet.create({
  container: { flex: 1, backgroundColor: COLORS.bg },
  notice:    { backgroundColor: COLORS.light, padding: 10, margin: 12, borderRadius: 8 },
  noticeText:{ fontSize: 12, color: COLORS.blue },
  card:      { backgroundColor: '#fff', borderRadius: 10, padding: 14, marginBottom: 8, elevation: 1 },
  row:       { flexDirection: 'row', alignItems: 'center' },
  title:     { fontSize: 14, fontWeight: '700', color: COLORS.text, marginBottom: 4 },
  meta:      { fontSize: 12, color: COLORS.muted, marginBottom: 2 },
  statusCol: { alignItems: 'center', gap: 4 },
  badge:     { fontSize: 10, color: '#fff', paddingHorizontal: 6, paddingVertical: 2, borderRadius: 4, fontWeight: '700' },
  empty:     { textAlign: 'center', color: COLORS.muted, marginTop: 40 },
})
