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

export default function InstitutionCompareScreen() {
  const [rows, setRows] = useState<any[]>([])
  const [loading, setLoading] = useState(false)

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

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

  const max = Math.max(...rows.map(r => r.total_sr ?? 0), 1)

  return (
    <ScrollView
      style={{ flex: 1, backgroundColor: COLORS.bg }}
      refreshControl={<RefreshControl refreshing={loading} onRefresh={load} />}
    >
      {/* 헤더 */}
      <View style={s.thead}>
        <Text style={[s.th, { flex: 2 }]}>기관</Text>
        <Text style={s.th}>전체</Text>
        <Text style={s.th}>완료</Text>
        <Text style={s.th}>SLA</Text>
        <Text style={s.th}>처리율</Text>
      </View>

      {rows.map((item, i) => {
        const rate = item.total_sr > 0 ? Math.round((item.completed_sr / item.total_sr) * 100) : 0
        const barW = Math.round(((item.total_sr ?? 0) / max) * 100)
        const slaColor = (item.sla_compliance_rate ?? 0) >= 95 ? COLORS.success : (item.sla_compliance_rate ?? 0) >= 80 ? COLORS.warning : COLORS.danger
        return (
          <View key={i} style={s.row}>
            <View style={{ flex: 2 }}>
              <Text style={s.instName} numberOfLines={1}>{item.institution_name ?? item.inst_code}</Text>
              <View style={s.barBg}>
                <View style={[s.barFill, { width: `${barW}%` }]} />
              </View>
            </View>
            <Text style={s.td}>{item.total_sr ?? 0}</Text>
            <Text style={s.td}>{item.completed_sr ?? 0}</Text>
            <Text style={[s.td, { color: slaColor, fontWeight: '700' }]}>{item.sla_compliance_rate ?? 0}%</Text>
            <Text style={s.td}>{rate}%</Text>
          </View>
        )
      })}

      {rows.length === 0 && !loading && (
        <Text style={s.empty}>기관 데이터가 없습니다.</Text>
      )}
    </ScrollView>
  )
}

const s = StyleSheet.create({
  thead:    { flexDirection: 'row', backgroundColor: COLORS.gnbBg, paddingHorizontal: 12, paddingVertical: 10 },
  th:       { flex: 1, fontSize: 12, color: '#fff', fontWeight: '700', textAlign: 'center' },
  row:      { flexDirection: 'row', backgroundColor: '#fff', marginHorizontal: 8, marginTop: 4, borderRadius: 8, padding: 10, alignItems: 'center', gap: 4 },
  instName: { fontSize: 12, fontWeight: '700', color: COLORS.text, marginBottom: 4 },
  barBg:    { height: 4, backgroundColor: COLORS.border, borderRadius: 2 },
  barFill:  { height: 4, backgroundColor: COLORS.accent, borderRadius: 2 },
  td:       { flex: 1, fontSize: 12, color: COLORS.text, textAlign: 'center' },
  empty:    { textAlign: 'center', color: COLORS.muted, marginTop: 40 },
})
