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 client from '../../services/api'

const MEDAL = ['🥇', '🥈', '🥉']

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

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

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

  const maxScore = items[0]?.score ?? 1

  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}>이번 달 처리 성과</Text>}
      renderItem={({ item, index }) => {
        const score = item.score ?? item.closed_count ?? 0
        const barWidth = `${Math.round((score / maxScore) * 100)}%`
        return (
          <View style={s.row}>
            <Text style={s.rank}>{MEDAL[index] ?? `${index + 1}`}</Text>
            <View style={{ flex: 1 }}>
              <View style={s.nameRow}>
                <Text style={s.name}>{item.name ?? item.engineer_name}</Text>
                <Text style={s.score}>{score}건</Text>
              </View>
              <View style={s.bar}>
                <View style={[s.fill, { width: barWidth as any }]} />
              </View>
              <Text style={s.meta}>SLA: {item.sla_rate ?? '-'}% · 평점: {item.rating ?? '-'}</Text>
            </View>
          </View>
        )
      }}
    />
  )
}

const s = StyleSheet.create({
  header:  { fontSize: 16, fontWeight: '800', color: COLORS.text, marginBottom: 12 },
  row:     { flexDirection: 'row', alignItems: 'center', gap: 12, backgroundColor: '#fff', borderRadius: 10, padding: 14, marginBottom: 6, elevation: 1 },
  rank:    { fontSize: 22, width: 32, textAlign: 'center' },
  nameRow: { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 6 },
  name:    { fontSize: 14, fontWeight: '700', color: COLORS.text },
  score:   { fontSize: 14, fontWeight: '700', color: COLORS.accent },
  bar:     { height: 6, backgroundColor: COLORS.border, borderRadius: 3, overflow: 'hidden', marginBottom: 4 },
  fill:    { height: '100%', backgroundColor: COLORS.accent, borderRadius: 3 },
  meta:    { fontSize: 11, color: COLORS.muted },
  empty:   { textAlign: 'center', color: COLORS.muted, marginTop: 40 },
})
