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'

const SAVING_COLOR: Record<string, string> = { HIGH: COLORS.success, MEDIUM: COLORS.warning, LOW: COLORS.muted }

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

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const [r, s] = await Promise.all([
        client.get('/api/cost-optimizer/recommendations'),
        client.get('/api/mobile2/savings-dashboard'),
      ])
      setItems(r.data?.recommendations ?? r.data?.items ?? [])
      setSavings(s.data)
    } catch { setItems([]) } finally { setLoading(false) }
  }, [])

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

  const apply = (item: any) => {
    Alert.alert('조치 확인', `${item.title ?? item.resource}에 대한 비용 절감 조치를 SR로 등록하시겠습니까?`, [
      { text: '취소', style: 'cancel' },
      { text: 'SR 등록', onPress: async () => {
        try {
          await client.post('/api/tasks', { title: `비용 절감 조치: ${item.title ?? item.resource}`, description: item.action ?? item.description, priority: 'MEDIUM', sr_type: 'CHANGE' })
          Alert.alert('완료', 'SR이 등록됐습니다.')
        } catch { Alert.alert('오류', 'SR 등록에 실패했습니다.') }
      }},
    ])
  }

  return (
    <FlatList
      data={items}
      keyExtractor={(_, i) => String(i)}
      refreshControl={<RefreshControl refreshing={loading} onRefresh={load} />}
      ListEmptyComponent={<Text style={s.empty}>비용 절감 권고가 없습니다.</Text>}
      style={{ backgroundColor: COLORS.bg }}
      ListHeaderComponent={savings && (
        <View style={s.savings}>
          <Text style={s.savingsLabel}>이번달 절감 효과</Text>
          <Text style={s.savingsAmount}>₩{(savings.total_saved_krw ?? 0).toLocaleString()}</Text>
        </View>
      )}
      contentContainerStyle={{ padding: 12 }}
      renderItem={({ item }) => {
        const impact = item.impact ?? item.priority ?? 'MEDIUM'
        return (
          <View style={s.card}>
            <View style={s.header}>
              <Text style={[s.badge, { backgroundColor: SAVING_COLOR[impact] ?? COLORS.muted }]}>{impact}</Text>
              <Text style={s.saving}>절감 {item.estimated_saving_krw ? `₩${item.estimated_saving_krw.toLocaleString()}` : '-'}</Text>
            </View>
            <Text style={s.title}>{item.title ?? item.resource}</Text>
            <Text style={s.desc} numberOfLines={2}>{item.action ?? item.description ?? ''}</Text>
            <TouchableOpacity style={s.applyBtn} onPress={() => apply(item)}>
              <Text style={s.applyText}>SR로 조치</Text>
            </TouchableOpacity>
          </View>
        )
      }}
    />
  )
}

const s = StyleSheet.create({
  savings:       { backgroundColor: COLORS.success, borderRadius: 12, padding: 16, marginBottom: 8, alignItems: 'center' },
  savingsLabel:  { color: '#fff', fontSize: 12, opacity: 0.9 },
  savingsAmount: { color: '#fff', fontSize: 28, fontWeight: '800', marginTop: 4 },
  card:          { backgroundColor: '#fff', borderRadius: 10, padding: 14, marginBottom: 8, elevation: 1 },
  header:        { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 6 },
  badge:         { color: '#fff', fontSize: 10, fontWeight: '700', paddingHorizontal: 8, paddingVertical: 3, borderRadius: 4 },
  saving:        { fontSize: 12, color: COLORS.success, fontWeight: '700' },
  title:         { fontSize: 14, fontWeight: '700', color: COLORS.text, marginBottom: 4 },
  desc:          { fontSize: 12, color: COLORS.muted, marginBottom: 8 },
  applyBtn:      { backgroundColor: COLORS.light, borderRadius: 6, padding: 8, alignItems: 'center' },
  applyText:     { color: COLORS.blue, fontSize: 12, fontWeight: '700' },
  empty:         { textAlign: 'center', color: COLORS.muted, marginTop: 40 },
})
