import { useEffect, useState } from 'react'
import { ScrollView, StyleSheet, Text, View } from 'react-native'
import { useLocalSearchParams } from 'expo-router'
import { useTheme } from '../constants/ThemeContext'
import { type ThemeTokens } from '../constants/ItmsTheme'
import { Card, Loading, StatusPill, ErrText, SectionTitle } from '../components/ui'
import { rowTitle, rowStatus, rowEntries, pick } from '../constants/rows'
import { itmsAssetInfo, itmsErrorMessage, type RowMap } from './itmsApi'

/*
 * 자산 상세(ResourceManagerController /rem/getAssetInfo.do).
 * 목록 raw 를 그대로 파라미터로 넘겨 상세 보강(자산키 컬럼명이 기관별 상이 → raw 통째 전달).
 */
export default function AssetDetail() {
  const { raw } = useLocalSearchParams<{ raw?: string }>()
  const { t } = useTheme()
  const s = makeStyles(t)
  const seed: RowMap = raw ? safeParse(raw) : {}
  const [row, setRow] = useState<RowMap>(seed)
  const [loading, setLoading] = useState(Object.keys(seed).length > 0)
  const [err, setErr] = useState('')

  useEffect(() => {
    let alive = true
    if (Object.keys(seed).length === 0) { setLoading(false); return }
    ;(async () => {
      try {
        const detail = await itmsAssetInfo(seed)
        const merged = { ...seed, ...(detail?.resultVo ?? detail?.assetVo ?? detail ?? {}) }
        if (alive) setRow(merged)
      } catch (e) { if (alive) setErr(itmsErrorMessage(e)) }
      finally { if (alive) setLoading(false) }
    })()
    return () => { alive = false }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [raw])

  if (loading && Object.keys(seed).length === 0) return <Loading />

  return (
    <ScrollView style={s.wrap} contentContainerStyle={s.content}>
      <Text style={s.title}>{rowTitle(row)}</Text>
      <Text style={s.sub}>{pick(row, ['assetId', 'resrceId', 'resrceNo', 'mngNo', 'serialNo'])}</Text>
      {!!rowStatus(row) && <View style={{ marginTop: 8 }}><StatusPill label={rowStatus(row)} /></View>}
      <ErrText msg={err} />
      <SectionTitle style={s.mt}>상세 항목</SectionTitle>
      <Card>
        {rowEntries(row).map((e) => (
          <View key={e.key} style={s.row}>
            <Text style={s.k} numberOfLines={1}>{e.key}</Text>
            <Text style={s.v} numberOfLines={4}>{e.value}</Text>
          </View>
        ))}
      </Card>
      <View style={{ height: 24 }} />
    </ScrollView>
  )
}

function safeParse(raw: string): RowMap { try { return JSON.parse(raw) as RowMap } catch { return {} } }

const makeStyles = (t: ThemeTokens) => StyleSheet.create({
  wrap: { flex: 1, backgroundColor: t.bg },
  content: { padding: 16 },
  title: { color: t.text, fontSize: 19, fontWeight: '900' },
  sub: { color: t.muted, fontSize: 13, marginTop: 4 },
  mt: { marginTop: 20 },
  row: { flexDirection: 'row', justifyContent: 'space-between', gap: 12, paddingVertical: 8, borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: t.border },
  k: { color: t.muted, fontSize: 12, flexShrink: 0, maxWidth: '40%' },
  v: { color: t.text, fontSize: 13, fontWeight: '600', flex: 1, textAlign: 'right' },
})
