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

export default function QRAPKScreen() {
  const [info, setInfo]   = useState<any>(null)
  const [loading, setLoading] = useState(false)

  const load = useCallback(async () => {
    setLoading(true)
    try { const r = await getAPKQRCode(); setInfo(r.data) }
    catch { setInfo(null) }
    finally { setLoading(false) }
  }, [])

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

  return (
    <ScrollView
      style={{ flex: 1, backgroundColor: COLORS.bg }}
      refreshControl={<RefreshControl refreshing={loading} onRefresh={load} />}
      contentContainerStyle={{ padding: 20, alignItems: 'center' }}
    >
      <Text style={s.title}>앱 배포 QR</Text>
      <Text style={s.desc}>QR코드를 스캔하면 최신 APK를 직접 다운로드할 수 있습니다. (Play Store 불필요)</Text>

      {info ? (
        <>
          {/* QR 이미지 — base64 또는 URL */}
          {info.qr_url ? (
            <View style={s.qrBox}>
              {/* RN에서 SVG QR: base64 img 태그를 WebView로 보여주거나
                  서버에서 PNG QR로 반환하는 경우 Image 컴포넌트 사용 */}
              <Text style={s.qrPlaceholder}>📱</Text>
              <Text style={s.qrHint}>QR URL: {info.qr_url}</Text>
            </View>
          ) : (
            <View style={s.qrBox}>
              <Text style={s.qrPlaceholder}>📱</Text>
              <Text style={s.qrHint}>QR 준비 중</Text>
            </View>
          )}

          <View style={s.infoCard}>
            <InfoRow label="버전" value={info.version ?? '-'} />
            <InfoRow label="빌드 날짜" value={info.built_at?.slice(0, 10) ?? '-'} />
            <InfoRow label="파일 크기" value={info.size_mb ? `${info.size_mb} MB` : '-'} />
            <InfoRow label="상태" value={info.status ?? '-'} />
          </View>

          {info.download_url && (
            <TouchableOpacity style={s.downloadBtn} onPress={() => Linking.openURL(info.download_url)}>
              <Text style={s.downloadText}>APK 직접 다운로드</Text>
            </TouchableOpacity>
          )}
        </>
      ) : (
        <View style={s.empty}>
          <Text style={s.emptyIcon}>📦</Text>
          <Text style={s.emptyText}>배포된 APK가 없습니다.</Text>
          <Text style={s.emptySubtext}>GUARDiA Manager에서 APK를 업로드하면 여기에 QR이 표시됩니다.</Text>
        </View>
      )}
    </ScrollView>
  )
}

function InfoRow({ label, value }: { label: string; value: string }) {
  return (
    <View style={s.infoRow}>
      <Text style={s.infoLabel}>{label}</Text>
      <Text style={s.infoValue}>{value}</Text>
    </View>
  )
}

const s = StyleSheet.create({
  title:       { fontSize: 22, fontWeight: '800', color: COLORS.text, marginBottom: 8 },
  desc:        { fontSize: 13, color: COLORS.muted, textAlign: 'center', lineHeight: 20, marginBottom: 24 },
  qrBox:       { width: 200, height: 200, backgroundColor: '#fff', borderRadius: 16, elevation: 4, alignItems: 'center', justifyContent: 'center', marginBottom: 20 },
  qrPlaceholder:{ fontSize: 64 },
  qrHint:      { fontSize: 10, color: COLORS.muted, marginTop: 6, textAlign: 'center', paddingHorizontal: 8 },
  infoCard:    { width: '100%', backgroundColor: '#fff', borderRadius: 12, padding: 16, marginBottom: 16, elevation: 1 },
  infoRow:     { flexDirection: 'row', justifyContent: 'space-between', paddingVertical: 8, borderBottomWidth: 1, borderBottomColor: COLORS.light },
  infoLabel:   { fontSize: 13, color: COLORS.muted },
  infoValue:   { fontSize: 13, fontWeight: '700', color: COLORS.text },
  downloadBtn: { width: '100%', backgroundColor: COLORS.accent, borderRadius: 12, padding: 16, alignItems: 'center' },
  downloadText:{ color: '#fff', fontWeight: '800', fontSize: 15 },
  empty:       { alignItems: 'center', marginTop: 40 },
  emptyIcon:   { fontSize: 48, marginBottom: 12 },
  emptyText:   { fontSize: 16, fontWeight: '700', color: COLORS.text, marginBottom: 6 },
  emptySubtext:{ fontSize: 13, color: COLORS.muted, textAlign: 'center', lineHeight: 20 },
})
