import React, { useState } from 'react';
import { Alert, Pressable, ScrollView, StyleSheet, Text, View, Switch } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { TimePicker } from '../../components/ui/TimePicker';
import { Ionicons } from '@expo/vector-icons';
import { useTheme } from '../../theme';
import { useT } from '../../i18n';
import { useSettingsStore, type Locale, type ThemeMode } from '../../store/settingsStore';
import { Card } from '../../components/ui/Card';
import { ScreenHeader } from '../../components/layout/ScreenHeader';

export default function PreferencesScreen() {
  const { theme } = useTheme();
  const t = useT();

  // Settings State
  const themeMode = useSettingsStore(s => s.themeMode);
  const setThemeMode = useSettingsStore(s => s.setThemeMode);
  const locale = useSettingsStore(s => s.locale);
  const setLocale = useSettingsStore(s => s.setLocale);
  const appLockEnabled = useSettingsStore(s => s.appLockEnabled);
  const setAppLockEnabled = useSettingsStore(s => s.setAppLockEnabled);
  const reminderEnabled = useSettingsStore(s => s.reminderEnabled);
  const reminderHour = useSettingsStore(s => s.reminderHour);
  const reminderMinute = useSettingsStore(s => s.reminderMinute);
  const updateReminderConfig = useSettingsStore(s => s.updateReminderConfig);
  const [timePickerOpen, setTimePickerOpen] = useState(false);
  const numpadGlobalEntry = useSettingsStore(s => s.numpadGlobalEntry);
  const setNumpadGlobalEntry = useSettingsStore(s => s.setNumpadGlobalEntry);

  const THEME_OPTIONS: { mode: ThemeMode; labelKey: string }[] = [
    { mode: 'light', labelKey: 'settings.themeLight' },
    { mode: 'dark', labelKey: 'settings.themeDark' },
    { mode: 'system', labelKey: 'settings.themeSystem' },
  ];

  const LOCALE_OPTIONS: { locale: Locale; labelKey: string }[] = [
    { locale: 'zh', labelKey: 'settings.langZh' },
    { locale: 'en', labelKey: 'settings.langEn' },
  ];

  return (
    <SafeAreaView style={[styles.page, { backgroundColor: theme.colors.bgPrimary }]} edges={['top', 'bottom']}>
      <ScreenHeader title={t('settings.preferencesTitle')} />

      <ScrollView contentContainerStyle={[styles.content, { gap: theme.spacing.md }]}>
        {/* 外观设置 */}
        <Card title={t('settings.appearance')}>
          <Text style={[theme.typography.bodySmall, { color: theme.colors.fgSecondary, marginBottom: 8 }]}>
            {t('settings.themeMode')}
          </Text>
          <View style={styles.optionRow}>
            {THEME_OPTIONS.map(opt => {
              const active = themeMode === opt.mode;
              return (
                <Pressable
                  key={opt.mode}
                  onPress={() => setThemeMode(opt.mode)}
                  style={[
                    styles.option,
                    {
                      backgroundColor: active ? theme.colors.accent : theme.colors.bgTertiary,
                      borderColor: active ? theme.colors.accent : theme.colors.border,
                      borderRadius: theme.radii.sm,
                    },
                  ]}
                >
                  <Text style={{ color: active ? theme.colors.fgInverse : theme.colors.fgPrimary, fontWeight: active ? '700' : '400' }}>
                    {t(opt.labelKey)}
                  </Text>
                </Pressable>
              );
            })}
          </View>
        </Card>

        {/* 语言偏好 */}
        <Card title={t('settings.language')}>
          <Text style={[theme.typography.bodySmall, { color: theme.colors.fgSecondary, marginBottom: 8 }]}>
            {t('settings.selectLang')}
          </Text>
          <View style={styles.optionRow}>
            {LOCALE_OPTIONS.map(opt => {
              const active = locale === opt.locale;
              return (
                <Pressable
                  key={opt.locale}
                  onPress={() => setLocale(opt.locale)}
                  style={[
                    styles.option,
                    {
                      backgroundColor: active ? theme.colors.accent : theme.colors.bgTertiary,
                      borderColor: active ? theme.colors.accent : theme.colors.border,
                      borderRadius: theme.radii.sm,
                    },
                  ]}
                >
                  <Text style={{ color: active ? theme.colors.fgInverse : theme.colors.fgPrimary, fontWeight: active ? '700' : '400' }}>
                    {t(opt.labelKey)}
                  </Text>
                </Pressable>
              );
            })}
          </View>
        </Card>

        {/* 记账 */}
        <Card title={t('settings.entryTitle')}>
          <View style={styles.switchRow}>
            <Text style={[theme.typography.body, { color: theme.colors.fgPrimary, flex: 1 }]}>
              {t('settings.numpadEntry')}
            </Text>
            <Switch
              value={numpadGlobalEntry}
              onValueChange={setNumpadGlobalEntry}
              trackColor={{ false: theme.colors.bgTertiary, true: theme.colors.accent }}
              thumbColor={theme.colors.fgInverse}
            />
          </View>
          <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, marginTop: 6 }]}>
            {t('settings.numpadEntryDesc')}
          </Text>
        </Card>

        {/* 安全设置 */}
        <Card title={t('settings.security')}>
          <View style={styles.switchRow}>
            <Text style={[theme.typography.body, { color: theme.colors.fgPrimary, flex: 1 }]}>
              {t('settings.appLock')}
            </Text>
            <Switch
              value={appLockEnabled}
              onValueChange={async (val) => {
                if (val) {
                  // 开启：需要设置 PIN
                  const { hasPinSet } = await import('../../components/layout/LockScreen');
                  const hasPin = await hasPinSet();
                  if (!hasPin) {
                    // Alert.prompt 仅 iOS 可用；Android 直接开启（用户首次锁屏时设置）
                    // 这里简化处理：直接开启，用户在锁屏界面首次输入时即设置 PIN
                    // 完整版应弹出一个 Modal 含 TextInput（留后续优化）
                    Alert.alert(
                      t('settings.setPinDesc'),
                      undefined,
                      [
                        { text: t('common.cancel'), style: 'cancel', onPress: () => {} },
                        {
                          text: t('common.confirm'),
                          onPress: async () => {
                            // 设置一个默认空 PIN，用户可在锁屏界面修改
                            // 真实实现应弹出 PIN 输入 Modal
                            setAppLockEnabled(true);
                          },
                        },
                      ],
                    );
                  } else {
                    setAppLockEnabled(true);
                  }
                } else {
                  // 关闭：清除 PIN
                  const { clearPin } = await import('../../components/layout/LockScreen');
                  await clearPin();
                  setAppLockEnabled(false);
                }
              }}
              trackColor={{ false: theme.colors.bgTertiary, true: theme.colors.accent }}
              thumbColor={theme.colors.fgInverse}
            />
          </View>
        </Card>

        {/* 每日记账提醒 */}
        <Card title={t('settings.reminderTitle')}>
          <View style={styles.switchRow}>
            <Text style={[theme.typography.body, { color: theme.colors.fgPrimary, flex: 1 }]}>
              {t('settings.reminderToggle')}
            </Text>
            <Switch
              value={reminderEnabled}
              onValueChange={async (val) => {
                updateReminderConfig({ reminderEnabled: val });
                try {
                  const { RealNotificationScheduler, setupDailyReminder, cancelAllReminders } = await import('../../services/reminder');
                  const scheduler = new RealNotificationScheduler();
                  if (val) {
                    await setupDailyReminder(scheduler, reminderHour, reminderMinute);
                  } else {
                    await cancelAllReminders(scheduler);
                  }
                } catch (e) {
                  Alert.alert(String(e));
                }
              }}
              trackColor={{ false: theme.colors.bgTertiary, true: theme.colors.accent }}
              thumbColor={theme.colors.fgInverse}
            />
          </View>
          {reminderEnabled && (
            <View style={[styles.switchRow, { marginTop: 12 }]}>
              <Text style={[theme.typography.body, { color: theme.colors.fgPrimary, flex: 1 }]}>
                {t('settings.reminderTime')}
              </Text>
              <Pressable
                onPress={() => setTimePickerOpen(true)}
                accessibilityRole="button"
                accessibilityLabel={t('settings.reminderTime')}
                style={{ flexDirection: 'row', alignItems: 'center', gap: 4 }}
              >
                <Text style={[theme.typography.body, { color: theme.colors.accent, fontWeight: '700', fontVariant: ['tabular-nums'] }]}>
                  {String(reminderHour).padStart(2, '0')}:{String(reminderMinute).padStart(2, '0')}
                </Text>
                <Ionicons name="chevron-forward" size={16} color={theme.colors.accent} />
              </Pressable>
            </View>
          )}
        </Card>
      </ScrollView>
      <TimePicker
        visible={timePickerOpen}
        hour={reminderHour}
        minute={reminderMinute}
        title={t('settings.reminderTime')}
        onCancel={() => setTimePickerOpen(false)}
        onConfirm={async (h, m) => {
          setTimePickerOpen(false);
          updateReminderConfig({ reminderHour: h, reminderMinute: m });
          const { RealNotificationScheduler, setupDailyReminder } = await import('../../services/reminder');
          await setupDailyReminder(new RealNotificationScheduler(), h, m);
        }}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  page: { flex: 1 },
  content: { padding: 16 },
  optionRow: { flexDirection: 'row', gap: 8 },
  option: { flex: 1, alignItems: 'center', paddingVertical: 8, borderWidth: 1 },
  switchRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
});
