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

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

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

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

  const assign = async (item: any) => {
    try {
      await client.post('/api/tasks', { title: `[민원] ${item.title ?? item.subject}`, description: item.description ?? item.content, priority: 'HIGH', sr_type: 'REQUEST', source: 'citizen_portal' })
      Alert.alert('완료', 'SR로 전환됐습니다.')
      load()
    } catch { Alert.alert('오류', '전환에 실패했습니다.') }
  }

  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 }) => (
        <View style={s.card}>
          <View style={s.row}>
            <View style={{ flex: 1 }}>
              <Text style={s.title} numberOfLines={1}>{item.title ?? item.subject}</Text>
              <Text style={s.meta}>{item.citizen_name ?? '익명'} · {item.created_at?.slice(0, 16) ?? ''}</Text>
            </View>
            <View style={[s.statusBadge, { backgroundColor: item.status === 'pending' ? COLORS.warning + '20' : COLORS.success + '20' }]}>
              <Text style={[s.statusText, { color: item.status === 'pending' ? COLORS.warning : COLORS.success }]}>{item.status === 'pending' ? '대기' : '처리중'}</Text>
            </View>
          </View>
          <Text style={s.desc} numberOfLines={2}>{item.description ?? item.content ?? ''}</Text>
          {item.status === 'pending' && (
            <TouchableOpacity style={s.srBtn} onPress={() => assign(item)}>
              <Text style={s.srText}>SR 전환</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 },
  statusBadge: { borderRadius: 4, paddingHorizontal: 8, paddingVertical: 3 },
  statusText:  { fontSize: 11, fontWeight: '700' },
  desc:        { fontSize: 12, color: COLORS.muted, marginBottom: 10 },
  srBtn:       { backgroundColor: COLORS.blue + '15', borderRadius: 6, padding: 8, alignItems: 'center' },
  srText:      { color: COLORS.blue, fontSize: 12, fontWeight: '700' },
  empty:       { textAlign: 'center', color: COLORS.muted, marginTop: 40 },
})
