/*
 * 더보기 — 계정 정보·API 상태(health)·로그아웃.
 */
import { Ionicons } from '@expo/vector-icons';
import { router } from 'expo-router';
import React, { useCallback, useEffect, useState } from 'react';
import { Pressable, ScrollView, StyleSheet, Text, View } from 'react-native';
import { Avatar } from '../../components/Avatar';
import { Card } from '../../components/Card';
import { useAuth } from '../../context/AuthContext';
import { api, isDegraded } from '../../lib/api';
import { API_BASE } from '../../lib/config';
import type { HealthDto } from '../../lib/types';
import { colors, radius, spacing, touch, type } from '../../theme';

export default function MoreScreen() {
  const { user, signOut } = useAuth();
  const [health, setHealth] = useState<string>('확인 중…');

  const checkHealth = useCallback(async () => {
    try {
      const res = await api.get<HealthDto>('/health', { anonymous: true });
      setHealth(res?.status === 'UP' ? '정상 (UP)' : (res?.status ?? '알 수 없음'));
    } catch (e) {
      setHealth(isDegraded(e) ? '연결 불가 (degraded)' : '오류');
    }
  }, []);

  useEffect(() => {
    checkHealth();
  }, [checkHealth]);

  async function onSignOut() {
    await signOut();
    router.replace('/login');
  }

  return (
    <ScrollView contentContainerStyle={styles.scroll}>
      {/* 내 정보 진입 — 프로필/생체인식 잠금/사진 등록 (SCR-M 내정보) */}
      <Pressable
        onPress={() => router.push('/profile')}
        accessibilityRole="button"
        accessibilityLabel="내 정보 열기"
      >
        <Card>
          <View style={styles.meRow}>
            <Avatar name={user?.displayName} size={48} />
            <View style={{ flex: 1, marginLeft: 12 }}>
              <Text style={styles.name}>{user?.displayName ?? '사용자'}</Text>
              <Text style={styles.meta}>
                {user?.hallManager ? '킨텍스 내부 계정 (홀매니저)' : '일반 계정'}
              </Text>
            </View>
            <Ionicons name="chevron-forward" size={20} color={colors.neutral500} />
          </View>
        </Card>
      </Pressable>

      <Card>
        <Row label="API 서버" value={API_BASE} />
        <View style={styles.divider} />
        <Pressable style={styles.healthRow} onPress={checkHealth}>
          <Row label="서버 상태" value={health} />
          <Ionicons name="refresh" size={18} color={colors.primary600} />
        </Pressable>
      </Card>

      <Pressable style={styles.signOut} onPress={onSignOut}>
        <Ionicons name="log-out-outline" size={20} color={colors.error} />
        <Text style={styles.signOutText}>로그아웃</Text>
      </Pressable>

      <Text style={styles.version}>KINTEX AI 전시관리 · v0.1.0</Text>
    </ScrollView>
  );
}

function Row({ label, value }: { label: string; value: string }) {
  return (
    <View style={styles.row}>
      <Text style={styles.rowLabel}>{label}</Text>
      <Text style={styles.rowValue} numberOfLines={1}>
        {value}
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  scroll: { padding: spacing.md, gap: spacing.md },
  meRow: { flexDirection: 'row', alignItems: 'center' },
  name: { fontSize: type.h3.fontSize, fontWeight: '700', color: colors.neutral900 },
  meta: { marginTop: 4, color: colors.neutral500, fontSize: type.caption.fontSize },
  row: { flexDirection: 'row', justifyContent: 'space-between', gap: 12, paddingVertical: 4 },
  rowLabel: { color: colors.neutral500, fontSize: type.body.fontSize },
  rowValue: { flex: 1, textAlign: 'right', color: colors.neutral900, fontSize: type.body.fontSize },
  divider: { height: 1, backgroundColor: colors.neutral200, marginVertical: 6 },
  healthRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
  signOut: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 8,
    minHeight: touch.min,
    borderRadius: radius.sm,
    borderWidth: 1,
    borderColor: colors.error,
  },
  signOutText: { color: colors.error, fontSize: type.h3.fontSize, fontWeight: '600' },
  version: { textAlign: 'center', color: colors.neutral500, fontSize: type.caption.fontSize },
});
