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

const STATUS_COLOR: Record<string, string> = {
  SUCCESS: COLORS.success, COMPLETED: COLORS.success,
  FAILURE: COLORS.danger,  FAILED: COLORS.danger,
  RUNNING: COLORS.accent,  IN_PROGRESS: COLORS.accent,
}

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

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

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

  return (
    <FlatList
      data={items}
      keyExtractor={(_, i) => String(i)}
      refreshControl={<RefreshControl refreshing={loading} onRefresh={load} />}
      ListEmptyComponent={<Text style={s.empty}>배포 이력이 없습니다.</Text>}
      contentContainerStyle={{ padding: 12, paddingLeft: 40 }}
      style={{ backgroundColor: COLORS.bg }}
      renderItem={({ item, index }) => {
        const color = STATUS_COLOR[item.status ?? ''] ?? COLORS.muted
        const dur = item.duration_sec ? `${Math.ceil(item.duration_sec / 60)}분` : '-'
        return (
          <View style={s.row}>
            {/* 타임라인 */}
            <View style={s.timeline}>
              <View style={[s.dot, { backgroundColor: color }]} />
              {index < items.length - 1 && <View style={s.line} />}
            </View>
            <View style={s.content}>
              <View style={s.headerRow}>
                <Text style={s.project}>{item.project ?? 'N/A'}</Text>
                <View style={[s.badge, { backgroundColor: color }]}>
                  <Text style={s.badgeText}>{item.status ?? '-'}</Text>
                </View>
              </View>
              <Text style={s.meta}>{item.started_at?.slice(0, 16).replace('T', ' ')} · {dur} · {item.deployed_by ?? '-'}</Text>
            </View>
          </View>
        )
      }}
    />
  )
}

const s = StyleSheet.create({
  row:       { flexDirection: 'row', marginBottom: 0 },
  timeline:  { position: 'absolute', left: -28, top: 0, bottom: 0, alignItems: 'center', width: 16 },
  dot:       { width: 12, height: 12, borderRadius: 6, marginTop: 14 },
  line:      { flex: 1, width: 2, backgroundColor: COLORS.border, marginTop: 2 },
  content:   { flex: 1, backgroundColor: '#fff', borderRadius: 10, padding: 12, marginBottom: 8, elevation: 1 },
  headerRow: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 },
  project:   { fontSize: 14, fontWeight: '700', color: COLORS.text },
  badge:     { borderRadius: 4, paddingHorizontal: 6, paddingVertical: 2 },
  badgeText: { fontSize: 10, color: '#fff', fontWeight: '700' },
  meta:      { fontSize: 12, color: COLORS.muted },
  empty:     { textAlign: 'center', color: COLORS.muted, marginTop: 40 },
})
