import React, { useMemo } from 'react';
import { SectionList, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter, type Href } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { useTheme } from '../../theme';
import { useT } from '../../i18n';
import { Touchable } from '../../components/ui/Touchable';

interface NavItem {
  icon: keyof typeof Ionicons.glyphMap;
  label: string;
  path: Href;
}

interface NavSection {
  title: string;
  data: NavItem[];
}

export default function SettingsScreen() {
  const { theme } = useTheme();
  const t = useT();
  const router = useRouter();

  // 使用 useMemo 缓存分组数据，避免每次渲染重新创建
  const sections: NavSection[] = useMemo(() => [
    {
      title: t('settings.groupAccount'),
      data: [
        { icon: 'wallet-outline', label: t('account.title'), path: '/account' },
        { icon: 'list', label: t('settings.categories'), path: '/category' },
        { icon: 'pricetags', label: t('settings.tags'), path: '/tag' },
        { icon: 'pie-chart', label: t('settings.budgets'), path: '/budget' },
        { icon: 'card-outline', label: t('settings.creditCards'), path: '/credit-card' as Href },
        { icon: 'text-outline', label: t('remark.title'), path: '/remark-template' as Href },
      ],
    },
    {
      title: t('settings.groupAutomation'),
      data: [
        { icon: 'git-branch-outline', label: t('tab.rules'), path: '/rules' },
        { icon: 'repeat-outline', label: t('settings.recurringTitle'), path: '/recurring' },
        { icon: 'flash-outline', label: t('automation.title'), path: '/automation' as Href },
        { icon: 'download-outline', label: t('settings.import'), path: '/import' as Href },
      ],
    },
    {
      title: t('settings.groupData'),
      data: [
        { icon: 'cloud-upload-outline', label: t('settings.syncBackup'), path: '/settings/sync' },
        { icon: 'pulse-outline', label: t('settings.diagnostics'), path: '/settings/diagnostics' as Href },
        { icon: 'document-text-outline', label: t('settings.appLogs'), path: '/settings/logs' as Href },
      ],
    },
    {
      title: t('settings.groupPreferences'),
      data: [
        { icon: 'phone-portrait-outline', label: t('settings.preferencesEntry'), path: '/settings/preferences' },
        { icon: 'cog-outline', label: t('settings.llmTitle'), path: '/settings/ai' },
        { icon: 'chatbubble-ellipses-outline', label: t('ai.chatTitle'), path: '/ai/chat' as Href },
      ],
    },
  ], [t]);

  const renderSectionHeader = ({ section }: { section: NavSection }) => (
    <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, fontWeight: '600', letterSpacing: 0.3, marginBottom: 6, marginTop: theme.spacing.md }]}>
      {section.title}
    </Text>
  );

  const renderItem = ({ item }: { item: NavItem }) => {
    const section = sections.find(s => s.data.includes(item));
    const isLast = section ? section.data[section.data.length - 1] === item : false;
    const isFirst = section ? section.data[0] === item : false;
    return (
      <Touchable
        onPress={() => router.push(item.path)}
        accessibilityRole="link"
        accessibilityLabel={item.label}
        style={[
          styles.navRow,
          {
            borderBottomColor: theme.colors.divider,
            borderBottomWidth: isLast ? 0 : StyleSheet.hairlineWidth,
            backgroundColor: theme.colors.bgSecondary,
            // 分组首行圆角顶 + 末行圆角底，配合 overflow hidden 形成圆角卡片组
            borderTopLeftRadius: isFirst ? theme.radii.lg : 0,
            borderTopRightRadius: isFirst ? theme.radii.lg : 0,
            borderBottomLeftRadius: isLast ? theme.radii.lg : 0,
            borderBottomRightRadius: isLast ? theme.radii.lg : 0,
          },
        ]}
      >
        <View style={styles.navIcon}>
          <Ionicons name={item.icon} size={20} color={theme.colors.accent} />
        </View>
        <Text style={[theme.typography.body, { color: theme.colors.fgPrimary, flex: 1 }]}>
          {item.label}
        </Text>
        <Ionicons name="chevron-forward" size={18} color={theme.colors.fgSecondary} />
      </Touchable>
    );
  };

  const AboutFooter = () => (
    <View style={{ marginTop: theme.spacing.md }}>
      <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, fontWeight: '600', letterSpacing: 0.3, marginBottom: 6 }]}>
        {t('settings.aboutTitle')}
      </Text>
      <View style={[styles.aboutCard, { backgroundColor: theme.colors.bgSecondary, borderRadius: theme.radii.md, borderColor: theme.colors.border }]}>
        <View style={styles.aboutRow}>
          <Text style={[theme.typography.body, { color: theme.colors.fgPrimary, fontWeight: '700' }]}>
            {t('app.name')}
          </Text>
          <Text style={[theme.typography.bodySmall, { color: theme.colors.fgSecondary }]}>
            {t('settings.aboutVersion')}
          </Text>
        </View>
        <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, marginTop: 8, lineHeight: 18 }]}>
          {t('app.tagline')}
        </Text>
      </View>
    </View>
  );

  return (
    <SafeAreaView style={[styles.page, { backgroundColor: theme.colors.bgPrimary }]} edges={['top']}>
      <View style={styles.header}>
        <Text style={[theme.typography.h1, { color: theme.colors.fgPrimary }]}>{t('tab.settings')}</Text>
      </View>

      <SectionList
        sections={sections}
        keyExtractor={(item) => item.label}
        renderSectionHeader={renderSectionHeader}
        renderItem={renderItem}
        ListFooterComponent={AboutFooter}
        stickySectionHeadersEnabled={false}
        contentContainerStyle={styles.content}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  page: { flex: 1 },
  header: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, paddingTop: 8, paddingBottom: 12 },
  content: { paddingHorizontal: 16, paddingBottom: 64 },
  navRow: {
    flexDirection: 'row',
    alignItems: 'center',
    // 行内自带左右 padding，图标与文字不再贴边
    paddingHorizontal: 16,
    paddingVertical: 14,
    overflow: 'hidden',
  },
  navIcon: {
    width: 32,
    height: 32,
    borderRadius: 8,
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: 14,
  },
  aboutCard: { padding: 16, borderWidth: StyleSheet.hairlineWidth },
  aboutRow: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' },
});
