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

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

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

  const urgency = (days: number) => days <= 30 ? COLORS.danger : days <= 90 ? COLORS.warning : COLORS.success

  const createSR = async (item: any) => {
    try {
      await client.post('/api/tasks', { title: `보증 만료 조치: ${item.asset_name ?? item.name}`, description: `${item.days_left ?? '?'}일 후 보증 만료 — 교체/연장 검토 필요`, priority: item.days_left <= 30 ? 'HIGH' : 'MEDIUM', sr_type: 'CHANGE' })
      Alert.alert('완료', 'SR이 등록됐습니다.')
    } catch { Alert.alert('오류', 'SR 등록에 실패했습니다.') }
  }

  return (
    <FlatList
      data={items.sort((a, b) => (a.days_left ?? 9999) - (b.days_left ?? 9999))}
      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 }) => {
        const days = item.days_left ?? item.warranty_days_left ?? 999
        const color = urgency(days)
        return (
          <View style={s.card}>
            <View style={s.row}>
              <View style={{ flex: 1 }}>
                <Text style={s.name}>{item.asset_name ?? item.name}</Text>
                <Text style={s.meta}>{item.manufacturer ?? '-'} {item.model ?? '-'} · {item.serial_no ?? ''}</Text>
              </View>
              <View style={[s.daysBadge, { backgroundColor: color }]}>
                <Text style={s.daysNum}>{days === 999 ? '∞' : days}</Text>
                <Text style={s.daysLabel}>일</Text>
              </View>
            </View>
            <Text style={s.expiry}>보증 만료: {item.warranty_end?.slice(0, 10) ?? '-'}</Text>
            {days <= 90 && (
              <TouchableOpacity style={s.srBtn} onPress={() => createSR(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: 12, marginBottom: 6 },
  name:      { fontSize: 14, fontWeight: '700', color: COLORS.text },
  meta:      { fontSize: 11, color: COLORS.muted, marginTop: 3 },
  daysBadge: { alignItems: 'center', borderRadius: 8, paddingVertical: 6, paddingHorizontal: 10 },
  daysNum:   { fontSize: 20, fontWeight: '900', color: '#fff' },
  daysLabel: { fontSize: 9, color: '#fff' },
  expiry:    { fontSize: 11, color: COLORS.muted, marginBottom: 8 },
  srBtn:     { backgroundColor: COLORS.warning + '20', borderRadius: 6, padding: 8, alignItems: 'center' },
  srText:    { color: COLORS.warning, fontSize: 12, fontWeight: '700' },
  empty:     { textAlign: 'center', color: COLORS.muted, marginTop: 40 },
})
