/**
 * 引导流程 Onboarding（plan.md「0.7 引导流程」）。
 *
 * 参考 BeeCount 的 Introduction 流程，新用户首次使用时引导完成基础配置：
 * 1. 欢迎页 + 应用介绍
 * 2. 语言选择（中/英）
 * 3. 主题选择（浅色/深色/跟随系统）
 * 4. 账本导入说明
 * 5. 功能启用说明（OCR/通知/短信权限）
 * 6. 安全设置（应用锁）
 *
 * 完成后标记 onboarding 已完成（持久化），后续启动不再显示。
 */

import React, { useState, useEffect } from 'react';
import { AppState, Platform, PermissionsAndroid, Linking, Pressable, ScrollView, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { useTheme } from '../theme';
import { useT } from '../i18n';
import { useSettingsStore, type Locale, type ThemeMode } from '../store/settingsStore';
import { Button } from '../components/ui/Button';
import { getAccessibilityBridge } from '../services/automation/accessibilityBridge';
import { Card } from '../components/ui/Card';

export interface OnboardingStep {
  key: string;
  title: string;
  description?: string;
}

interface OnboardingProps {
  onComplete: () => void;
}

export function OnboardingScreen({ onComplete }: OnboardingProps) {
  const { theme } = useTheme();
  const t = useT();
  const setLocale = useSettingsStore(s => s.setLocale);
  const setThemeMode = useSettingsStore(s => s.setThemeMode);
  const setAppLockEnabled = useSettingsStore(s => s.setAppLockEnabled);
  const appLockEnabled = useSettingsStore(s => s.appLockEnabled);
  const [step, setStep] = useState(0);

  const steps: OnboardingStep[] = [
    { key: 'welcome', title: t('app.name'), description: t('app.tagline') },
    { key: 'language', title: t('onboarding.language') },
    { key: 'theme', title: t('onboarding.theme') },
    { key: 'ledger', title: t('onboarding.ledger'), description: t('onboarding.ledgerDesc') },
    { key: 'permissions', title: t('onboarding.permissions'), description: t('onboarding.permissionsDesc') },
    { key: 'security', title: t('onboarding.security'), description: t('onboarding.securityDesc') },
  ];

  const current = steps[step];
  const isLast = step === steps.length - 1;

  // ── 权限状态管理（P7 Task 2） ──
  const [permStates, setPermStates] = useState<Record<string, boolean | null>>({
    accessibility: null, notification: null, sms: null, storage: null, overlay: null,
  });
  const permsChecked = !Object.values(permStates).some(v => v === null);
  const allGranted = permsChecked && Object.values(permStates).every(Boolean);

  useEffect(() => {
    if (Platform.OS !== 'android') return;

    const checkAllPermissions = async () => {
      if (current.key !== 'permissions') return;
      const bridge = getAccessibilityBridge();
      let a = false, n = false, o = false, s = false, st = false;
      if (bridge) {
        try { a = await bridge.isServiceRunning(); } catch { /* false */ }
        try { n = await bridge.isNotificationListenerEnabled(); } catch { /* false */ }
        try { o = await bridge.canDrawOverlays(); } catch { /* false */ }
      }
      try { s = await PermissionsAndroid.check('android.permission.RECEIVE_SMS') as boolean; } catch { /* false */ }
      const storagePerm = parseInt(String(Platform.Version), 10) >= 33
        ? 'android.permission.READ_MEDIA_IMAGES' : 'android.permission.READ_EXTERNAL_STORAGE';
      try { st = await PermissionsAndroid.check(storagePerm) as boolean; } catch { /* false */ }
      setPermStates({ accessibility: a, notification: n, overlay: o, sms: s, storage: st });
    };

    checkAllPermissions();

    // 从系统设置返回后重新检查
    const sub = AppState.addEventListener('change', (state) => {
      if (state === 'active') checkAllPermissions();
    });
    return () => sub.remove();
  }, [current.key]);

  const handlePermAction = async (key: string) => {
    const storagePerm = parseInt(String(Platform.Version), 10) >= 33
      ? 'android.permission.READ_MEDIA_IMAGES'
      : 'android.permission.READ_EXTERNAL_STORAGE';
    switch (key) {
      case 'accessibility':
        await Linking.sendIntent('android.settings.ACCESSIBILITY_SETTINGS');
        break;
      case 'notification':
        await Linking.sendIntent('android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS');
        break;
      case 'sms': {
        const result = await PermissionsAndroid.request('android.permission.RECEIVE_SMS');
        setPermStates(p => ({ ...p, sms: result === PermissionsAndroid.RESULTS.GRANTED }));
        break;
      }
      case 'storage': {
        const result = await PermissionsAndroid.request(storagePerm);
        setPermStates(p => ({ ...p, storage: result === PermissionsAndroid.RESULTS.GRANTED }));
        break;
      }
      case 'overlay':
        await Linking.sendIntent('android.settings.action.MANAGE_OVERLAY_PERMISSION');
        break;
    }
  };

  return (
    <SafeAreaView style={[styles.page, { backgroundColor: theme.colors.bgPrimary }]}>
      <ScrollView contentContainerStyle={styles.content}>
        <View style={styles.iconWrap}>
          <Ionicons name="book-outline" size={64} color={theme.colors.accent} />
        </View>
        <Text style={[theme.typography.h1, { color: theme.colors.fgPrimary, textAlign: 'center' }]}>
          {current.title}
        </Text>
        {current.description && (
          <Text style={[theme.typography.body, { color: theme.colors.fgSecondary, textAlign: 'center', marginTop: 12 }]}>
            {current.description}
          </Text>
        )}

        {current.key === 'language' && (
          <View style={styles.options}>
            {(['zh', 'en'] as Locale[]).map(loc => (
              <Pressable
                key={loc}
                onPress={() => setLocale(loc)}
                style={[styles.option, { backgroundColor: theme.colors.bgTertiary, borderColor: theme.colors.border }]}
              >
                <Text style={{ color: theme.colors.fgPrimary }}>{loc === 'zh' ? t('settings.langZh') : t('settings.langEn')}</Text>
              </Pressable>
            ))}
          </View>
        )}

        {current.key === 'theme' && (
          <View style={styles.options}>
            {(['light', 'dark', 'system'] as ThemeMode[]).map(mode => (
              <Pressable
                key={mode}
                onPress={() => setThemeMode(mode)}
                style={[styles.option, { backgroundColor: theme.colors.bgTertiary, borderColor: theme.colors.border }]}
              >
                <Text style={{ color: theme.colors.fgPrimary }}>
                  {mode === 'light' ? t('settings.themeLight') : mode === 'dark' ? t('settings.themeDark') : t('settings.themeSystem')}
                </Text>
              </Pressable>
            ))}
          </View>
        )}

        {current.key === 'permissions' && Platform.OS === 'android' && (
          <View style={{ width: '100%', marginTop: 24 }}>
            <Card>
              {[
                { key: 'accessibility', icon: 'accessibility-outline' as const, label: t('onboarding.permAccessibility') },
                { key: 'notification', icon: 'notifications-outline' as const, label: t('onboarding.permNotification') },
                { key: 'sms', icon: 'chatbubble-outline' as const, label: t('onboarding.permSms') },
                { key: 'storage', icon: 'images-outline' as const, label: t('onboarding.permStorage') },
                { key: 'overlay', icon: 'tablet-landscape-outline' as const, label: t('onboarding.permOverlay') },
              ].map(item => {
                const status = permStates[item.key];
                const granted = status === true;
                const statusColor = granted ? theme.colors.success : theme.colors.fgSecondary;
                const statusText = status === null ? '...' : granted ? t('onboarding.permGranted') : t('onboarding.permNotGranted');
                return (
                  <View key={item.key} style={styles.permRow}>
                    <View style={styles.permLeft}>
                      <Ionicons name={item.icon} size={20} color={granted ? theme.colors.success : theme.colors.fgSecondary} />
                      <Text style={[theme.typography.body, { color: theme.colors.fgPrimary, marginLeft: 12 }]}>
                        {item.label}
                      </Text>
                    </View>
                    <View style={styles.permRight}>
                      <Text style={[theme.typography.caption, { color: statusColor, marginRight: 8 }]}>
                        {statusText}
                      </Text>
                      {!granted && !allGranted && (
                        <Button
                          label={item.key === 'sms' || item.key === 'storage' ? t('onboarding.permRequest') : t('onboarding.permOpenSettings')}
                          onPress={() => handlePermAction(item.key)}
                          variant="secondary"
                        />
                      )}
                    </View>
                  </View>
                );
              })}
            </Card>
            {allGranted && (
              <View style={styles.allGrantedWrap}>
                <Ionicons name="checkmark-circle" size={48} color={theme.colors.success} />
                <Text style={[theme.typography.body, { color: theme.colors.success, marginTop: 8 }]}>
                  {t('onboarding.permAllDone')}
                </Text>
              </View>
            )}
          </View>
        )}

        {current.key === 'security' && (
          <Pressable
            onPress={() => setAppLockEnabled(!appLockEnabled)}
            style={[styles.option, { backgroundColor: theme.colors.bgTertiary, borderColor: theme.colors.border, marginTop: 16 }]}
          >
            <Text style={{ color: theme.colors.fgPrimary }}>
              {appLockEnabled ? t('onboarding.lockEnabled') : t('onboarding.enableLock')}
            </Text>
          </Pressable>
        )}
      </ScrollView>

      <View style={[styles.footer, { borderTopColor: theme.colors.border }]}>
        <View style={styles.dots}>
          {steps.map((_, i) => (
            <View
              key={i}
              style={[styles.dot, { backgroundColor: i === step ? theme.colors.accent : theme.colors.border }]}
            />
          ))}
        </View>
        <View style={styles.actions}>
          {step > 0 && (
            <Button label={t('onboarding.prev')} onPress={() => setStep(step - 1)} variant="secondary" />
          )}
          {isLast ? (
            <Button label={t('onboarding.start')} onPress={onComplete} />
          ) : (
            <Button label={t('onboarding.next')} onPress={() => setStep(step + 1)} />
          )}
        </View>
      </View>
    </SafeAreaView>
  );
}

/** 默认导出（expo-router 兼容性，消除「missing default export」警告）。 */
export default OnboardingScreen;

const styles = StyleSheet.create({
  page: { flex: 1 },
  content: { flex: 1, padding: 24, alignItems: 'center', justifyContent: 'center' },
  iconWrap: { marginBottom: 24 },
  options: { flexDirection: 'row', gap: 12, marginTop: 24, flexWrap: 'wrap', justifyContent: 'center' },
  option: { paddingVertical: 12, paddingHorizontal: 24, borderRadius: 12, borderWidth: 1 },
  footer: { padding: 16, borderTopWidth: 1 },
  dots: { flexDirection: 'row', justifyContent: 'center', gap: 6, marginBottom: 12 },
  dot: { width: 8, height: 8, borderRadius: 4 },
  actions: { flexDirection: 'row', gap: 12, justifyContent: 'flex-end' },
  // 权限清单（P7 Task 2）
  permRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingVertical: 8 },
  permLeft: { flexDirection: 'row', alignItems: 'center', flex: 1 },
  permRight: { flexDirection: 'row', alignItems: 'center' },
  allGrantedWrap: { alignItems: 'center', marginTop: 24 },
});
