import React, { useState, useCallback } from 'react'
import { View, Text, FlatList, TouchableOpacity, StyleSheet, Alert, RefreshControl } from 'react-native'
import { useFocusEffect } from 'expo-router'
import { COLORS } from '../../constants/Config'
import { getBuilds, triggerBuild } from '../../services/api'

const STATUS_COLOR: Record<string, string> = {
  SUCCESS: COLORS.success,
  FAILURE: COLORS.danger,
  RUNNING: COLORS.accent,
  ABORTED: COLORS.muted,
}
const STATUS_ICON: Record<string, string> = {
  SUCCESS: '✅', FAILURE: '❌', RUNNING: '⏳', ABORTED: '⏹',
}

export default function JenkinsBuildsScreen() {
  const [builds, setBuilds] = useState<any[]>([])
  const [loading, setLoading] = useState(false)

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

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

  const trigger = (project: string) => {
    Alert.alert('빌드 트리거', `${project} 빌드를 시작하시겠습니까?`, [
      { text: '취소', style: 'cancel' },
      { text: '시작', onPress: async () => {
        try {
          await triggerBuild(project)
          Alert.alert('완료', '빌드가 대기열에 추가됐습니다.')
          setTimeout(load, 1000)
        } catch { Alert.alert('오류', '빌드 트리거에 실패했습니다.') }
      }},
    ])
  }

  const renderItem = ({ item }: { item: any }) => {
    const color = STATUS_COLOR[item.status ?? 'ABORTED'] ?? COLORS.muted
    const icon  = STATUS_ICON[item.status ?? 'ABORTED'] ?? '❓'
    const dur   = item.duration_sec ? `${Math.floor(item.duration_sec / 60)}분 ${item.duration_sec % 60}초` : '-'
    return (
      <View style={s.card}>
        <View style={s.row}>
          <Text style={s.icon}>{icon}</Text>
          <View style={{ flex: 1 }}>
            <Text style={s.project}>{item.project}</Text>
            <Text style={s.meta}>{item.branch} · {item.started_at?.slice(0, 16).replace('T', ' ')}</Text>
          </View>
          <View>
            <Text style={[s.status, { color }]}>{item.status}</Text>
            <Text style={s.dur}>{dur}</Text>
          </View>
        </View>
        <TouchableOpacity style={s.retrigger} onPress={() => trigger(item.project)}>
          <Text style={s.retriggerText}>재실행</Text>
        </TouchableOpacity>
      </View>
    )
  }

  return (
    <FlatList
      data={builds}
      keyExtractor={(_, i) => String(i)}
      renderItem={renderItem}
      refreshControl={<RefreshControl refreshing={loading} onRefresh={load} />}
      ListEmptyComponent={<Text style={s.empty}>빌드 이력이 없습니다.</Text>}
      contentContainerStyle={{ padding: 12 }}
      style={{ backgroundColor: COLORS.bg }}
    />
  )
}

const s = StyleSheet.create({
  card:         { backgroundColor: '#fff', borderRadius: 10, padding: 14, marginBottom: 8, elevation: 1 },
  row:          { flexDirection: 'row', alignItems: 'center', gap: 10 },
  icon:         { fontSize: 22 },
  project:      { fontSize: 14, fontWeight: '700', color: COLORS.text },
  meta:         { fontSize: 12, color: COLORS.muted, marginTop: 2 },
  status:       { fontSize: 12, fontWeight: '700', textAlign: 'right' },
  dur:          { fontSize: 11, color: COLORS.muted, textAlign: 'right', marginTop: 2 },
  retrigger:    { marginTop: 10, backgroundColor: COLORS.light, borderRadius: 6, padding: 6, alignItems: 'center' },
  retriggerText:{ fontSize: 12, color: COLORS.blue, fontWeight: '600' },
  empty:        { textAlign: 'center', color: COLORS.muted, marginTop: 40 },
})
