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 TodoListScreen() {
  const [items, setItems] = useState<any[]>([])
  const [loading, setLoading] = useState(false)

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const r = await client.get('/api/tasks', { params: { assigned: 'me', status: 'open', size: 50 } })
      setItems(r.data?.items ?? r.data ?? [])
    } catch { setItems([]) } finally { setLoading(false) }
  }, [])

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

  const close = (item: any) => {
    Alert.alert('완료 처리', `SR #${item.id}를 완료 처리하시겠습니까?`, [
      { text: '취소', style: 'cancel' },
      { text: '완료', onPress: async () => {
        try {
          await client.patch(`/api/tasks/${item.id}`, { status: 'CLOSED' })
          setItems(prev => prev.filter(t => t.id !== item.id))
        } catch { Alert.alert('오류', '처리에 실패했습니다.') }
      }},
    ])
  }

  const prio = (p: string) => ({ CRITICAL: COLORS.danger, HIGH: '#f97316', MEDIUM: COLORS.warning, LOW: COLORS.muted }[p ?? 'LOW'] ?? COLORS.muted)

  return (
    <FlatList
      data={items}
      keyExtractor={item => String(item.id)}
      refreshControl={<RefreshControl refreshing={loading} onRefresh={load} />}
      ListEmptyComponent={<Text style={s.empty}>할 일이 없습니다.</Text>}
      style={{ backgroundColor: COLORS.bg }}
      contentContainerStyle={{ padding: 12 }}
      ListHeaderComponent={<Text style={s.count}>총 {items.length}건</Text>}
      renderItem={({ item }) => (
        <View style={[s.card, { borderLeftColor: prio(item.priority), borderLeftWidth: 4 }]}>
          <View style={s.row}>
            <View style={{ flex: 1 }}>
              <Text style={s.title} numberOfLines={1}>{item.title}</Text>
              <Text style={s.meta}>#{item.id} · {item.sr_type ?? item.type} · {item.due_date?.slice(0, 10) ?? '기한 없음'}</Text>
            </View>
            <TouchableOpacity style={s.doneBtn} onPress={() => close(item)}>
              <Text style={s.doneText}>완료</Text>
            </TouchableOpacity>
          </View>
        </View>
      )}
    />
  )
}

const s = StyleSheet.create({
  count:   { fontSize: 12, color: COLORS.muted, marginBottom: 8 },
  card:    { backgroundColor: '#fff', borderRadius: 10, padding: 14, marginBottom: 6, elevation: 1 },
  row:     { flexDirection: 'row', alignItems: 'center', gap: 10 },
  title:   { fontSize: 13, fontWeight: '700', color: COLORS.text },
  meta:    { fontSize: 11, color: COLORS.muted, marginTop: 3 },
  doneBtn: { backgroundColor: COLORS.success + '20', borderRadius: 6, paddingHorizontal: 10, paddingVertical: 6 },
  doneText:{ fontSize: 12, color: COLORS.success, fontWeight: '700' },
  empty:   { textAlign: 'center', color: COLORS.muted, marginTop: 40 },
})
