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

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

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

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

  const statusColor = (s: string) => ({ 진행중: COLORS.success, 입찰중: COLORS.blue, 마감: COLORS.muted, 낙찰: COLORS.accent }[s] ?? COLORS.muted)

  return (
    <FlatList
      data={items}
      keyExtractor={(_, i) => String(i)}
      refreshControl={<RefreshControl refreshing={loading} onRefresh={load} />}
      ListEmptyComponent={<Text style={s.empty}>나라장터 계약 데이터가 없습니다.</Text>}
      style={{ backgroundColor: COLORS.bg }}
      contentContainerStyle={{ padding: 12 }}
      ListHeaderComponent={<Text style={s.header}>나라장터 G2B 계약 현황</Text>}
      renderItem={({ item }) => {
        const st = item.status ?? '진행중'
        return (
          <View style={s.card}>
            <View style={s.row}>
              <View style={{ flex: 1 }}>
                <Text style={s.title} numberOfLines={1}>{item.contract_name ?? item.title}</Text>
                <Text style={s.meta}>{item.institution_name ?? item.org} · {item.amount ? `₩${Number(item.amount).toLocaleString()}` : '-'}</Text>
              </View>
              <View style={[s.badge, { backgroundColor: statusColor(st) + '20' }]}>
                <Text style={[s.badgeText, { color: statusColor(st) }]}>{st}</Text>
              </View>
            </View>
            <Text style={s.date}>기간: {item.start_date?.slice(0, 10) ?? '-'} ~ {item.end_date?.slice(0, 10) ?? '-'}</Text>
            {item.g2b_url && (
              <TouchableOpacity onPress={() => Linking.openURL(item.g2b_url)}>
                <Text style={s.link}>나라장터 바로가기 →</Text>
              </TouchableOpacity>
            )}
          </View>
        )
      }}
    />
  )
}

const s = StyleSheet.create({
  header:    { fontSize: 16, fontWeight: '800', color: COLORS.text, marginBottom: 12 },
  card:      { backgroundColor: '#fff', borderRadius: 10, padding: 14, marginBottom: 8, elevation: 1 },
  row:       { flexDirection: 'row', alignItems: 'center', gap: 8, marginBottom: 6 },
  title:     { fontSize: 13, fontWeight: '700', color: COLORS.text },
  meta:      { fontSize: 11, color: COLORS.muted, marginTop: 2 },
  badge:     { borderRadius: 4, paddingHorizontal: 8, paddingVertical: 3 },
  badgeText: { fontSize: 11, fontWeight: '700' },
  date:      { fontSize: 11, color: COLORS.muted, marginBottom: 6 },
  link:      { color: COLORS.blue, fontSize: 12, fontWeight: '700' },
  empty:     { textAlign: 'center', color: COLORS.muted, marginTop: 40 },
})
