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'

const STATE_COLOR: Record<string, string> = { running: COLORS.success, stopped: COLORS.muted, error: COLORS.danger, suspended: COLORS.warning }

export default function VMStatusScreen() {
  const [items, setItems] = useState<any[]>([])
  const [loading, setLoading] = useState(false)

  const load = useCallback(async () => {
    setLoading(true)
    try { const r = await client.get('/api/cloud/vms'); setItems(r.data?.vms ?? r.data?.items ?? []) }
    catch { setItems([]) } finally { setLoading(false) }
  }, [])

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

  const action = (vm: any, act: string) => {
    Alert.alert('VM 제어', `${vm.name}을(를) ${act} 하시겠습니까?`, [
      { text: '취소', style: 'cancel' },
      { text: '실행', onPress: async () => {
        try { await client.post(`/api/cloud/vms/${vm.id}/${act}`); load() }
        catch { Alert.alert('오류', '작업에 실패했습니다.') }
      }},
    ])
  }

  return (
    <FlatList
      data={items}
      keyExtractor={(_, i) => String(i)}
      refreshControl={<RefreshControl refreshing={loading} onRefresh={load} />}
      ListEmptyComponent={<Text style={s.empty}>VM 데이터가 없습니다.</Text>}
      style={{ backgroundColor: COLORS.bg }}
      contentContainerStyle={{ padding: 12 }}
      renderItem={({ item }) => {
        const state = item.state ?? item.status ?? 'stopped'
        const color = STATE_COLOR[state] ?? COLORS.muted
        return (
          <View style={s.card}>
            <View style={s.row}>
              <View style={[s.dot, { backgroundColor: color }]} />
              <View style={{ flex: 1 }}>
                <Text style={s.name}>{item.name}</Text>
                <Text style={s.meta}>{item.vcpus ?? '-'}vCPU · {item.memory_gb ?? '-'}GB · {item.os ?? '-'}</Text>
              </View>
              <Text style={[s.state, { color }]}>{state}</Text>
            </View>
            <View style={s.btnRow}>
              {state !== 'running' && <TouchableOpacity style={[s.btn, { backgroundColor: COLORS.success + '20' }]} onPress={() => action(item, 'start')}><Text style={[s.btnText, { color: COLORS.success }]}>시작</Text></TouchableOpacity>}
              {state === 'running' && <TouchableOpacity style={[s.btn, { backgroundColor: COLORS.danger + '20' }]} onPress={() => action(item, 'stop')}><Text style={[s.btnText, { color: COLORS.danger }]}>중지</Text></TouchableOpacity>}
              {state === 'running' && <TouchableOpacity style={[s.btn, { backgroundColor: COLORS.warning + '20' }]} onPress={() => action(item, 'reboot')}><Text style={[s.btnText, { color: COLORS.warning }]}>재부팅</Text></TouchableOpacity>}
            </View>
          </View>
        )
      }}
    />
  )
}

const s = StyleSheet.create({
  card:    { backgroundColor: '#fff', borderRadius: 10, padding: 14, marginBottom: 8, elevation: 1 },
  row:     { flexDirection: 'row', alignItems: 'center', gap: 10, marginBottom: 10 },
  dot:     { width: 10, height: 10, borderRadius: 5 },
  name:    { fontSize: 14, fontWeight: '700', color: COLORS.text },
  meta:    { fontSize: 11, color: COLORS.muted, marginTop: 2 },
  state:   { fontSize: 11, fontWeight: '700' },
  btnRow:  { flexDirection: 'row', gap: 8 },
  btn:     { flex: 1, borderRadius: 6, paddingVertical: 8, alignItems: 'center' },
  btnText: { fontSize: 12, fontWeight: '700' },
  empty:   { textAlign: 'center', color: COLORS.muted, marginTop: 40 },
})
