/**
 * LLM / AI 视觉配置页（P8）。
 *
 * 配置项：
 * - AI 服务商（openai / gemini / deepseek）
 * - API Key
 * - Base URL
 * - 模型名称
 * - AI 总开关
 */
import React, { useState } from 'react';
import { KeyboardAvoidingView, Platform, Pressable, ScrollView, StyleSheet, Text, TextInput, View, Switch } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useTheme } from '../../theme';
import { createCommonStyles } from '../../theme/commonStyles';
import { useT } from '../../i18n';
import { useSettingsStore } from '../../store/settingsStore';
import { Card } from '../../components/ui/Card';
import { ScreenHeader } from '../../components/layout/ScreenHeader';

const PROVIDERS: { key: string; label: string }[] = [
  { key: 'openai', label: 'OpenAI' },
  { key: 'gemini', label: 'Gemini' },
  { key: 'deepseek', label: 'DeepSeek' },
];

const PROVIDER_DEFAULT_URLS: Record<string, string> = {
  openai: 'https://api.openai.com/v1',
  gemini: 'https://generativelanguage.googleapis.com/v1beta',
  deepseek: 'https://api.deepseek.com/v1',
};

const PROVIDER_DEFAULT_MODELS: Record<string, string> = {
  openai: 'gpt-4o-mini',
  gemini: 'gemini-2.0-flash',
  deepseek: 'deepseek-chat',
};

export default function AiSettingsScreen() {
  const { theme } = useTheme();
  const commonStyles = createCommonStyles(theme);
  const t = useT();

  const aiEnabled = useSettingsStore(s => s.aiEnabled);
  const aiProviderId = useSettingsStore(s => s.aiProviderId);
  const aiApiKey = useSettingsStore(s => s.aiApiKey) || '';
  const aiBaseUrl = useSettingsStore(s => s.aiBaseUrl) || '';
  const aiModel = useSettingsStore(s => s.aiModel) || '';
  const updateAiConfig = useSettingsStore(s => s.updateAiConfig);

  const [localKey, setLocalKey] = useState(aiApiKey);
  const [localUrl, setLocalUrl] = useState(aiBaseUrl);
  const [localModel, setLocalModel] = useState(aiModel);

  const inputStyle = {
    backgroundColor: theme.colors.bgTertiary,
    color: theme.colors.fgPrimary,
    borderRadius: theme.radii.sm,
    padding: 12,
    fontSize: 14,
    marginTop: 6,
  };

  return (
    <SafeAreaView style={[styles.page, { backgroundColor: theme.colors.bgPrimary }]} edges={['top', 'bottom']}>
      <ScreenHeader title={t('settings.llmTitle')} />
      <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'} style={{ flex: 1 }}>
      <ScrollView contentContainerStyle={[styles.content, { gap: theme.spacing.md }]} keyboardShouldPersistTaps="handled" keyboardDismissMode="interactive">
        {/* AI 总开关 */}
        <Card>
          <View style={styles.row}>
            <Text style={[theme.typography.body, { color: theme.colors.fgPrimary, flex: 1 }]}>
              {t('settings.enableAiHint')}
            </Text>
            <Switch
              value={aiEnabled}
              onValueChange={val => updateAiConfig({ aiEnabled: val })}
              trackColor={{ false: theme.colors.bgTertiary, true: theme.colors.accent }}
              thumbColor={theme.colors.fgInverse}
            />
          </View>
        </Card>

        {/* 服务商选择 */}
        <Card title={t('automation.aiProviderLabel')}>
          <View style={styles.chipRow}>
            {PROVIDERS.map(p => (
              <Pressable
                key={p.key}
                onPress={() => updateAiConfig({ aiProviderId: p.key as 'openai' | 'gemini' | 'deepseek' })}
                style={[
                  commonStyles.chip,
                  aiProviderId === p.key && commonStyles.chipActive,
                ]}
              >
                <Text style={[commonStyles.chipText, aiProviderId === p.key && commonStyles.chipTextActive]}>
                  {p.label}
                </Text>
              </Pressable>
            ))}
          </View>
        </Card>

        {/* API Key */}
        <Card title={t('settings.aiFieldApiKey')}>
          <TextInput
            style={inputStyle}
            value={localKey}
            onChangeText={setLocalKey}
            onBlur={() => updateAiConfig({ aiApiKey: localKey })}
            placeholder="sk-..."
            placeholderTextColor={theme.colors.fgSecondary}
            secureTextEntry
            autoCapitalize="none"
            autoCorrect={false}
          />
        </Card>

        {/* Base URL */}
        <Card title={t('settings.aiFieldBaseUrl')}>
          <TextInput
            style={inputStyle}
            value={localUrl}
            onChangeText={setLocalUrl}
            onBlur={() => updateAiConfig({ aiBaseUrl: localUrl })}
            placeholder={PROVIDER_DEFAULT_URLS[aiProviderId] || PROVIDER_DEFAULT_URLS.openai}
            placeholderTextColor={theme.colors.fgSecondary}
            autoCapitalize="none"
            autoCorrect={false}
            keyboardType="url"
          />
        </Card>

        {/* 模型 */}
        <Card title={t('settings.aiFieldModel')}>
          <TextInput
            style={inputStyle}
            value={localModel}
            onChangeText={setLocalModel}
            onBlur={() => updateAiConfig({ aiModel: localModel })}
            placeholder={PROVIDER_DEFAULT_MODELS[aiProviderId] || PROVIDER_DEFAULT_MODELS.openai}
            placeholderTextColor={theme.colors.fgSecondary}
            autoCapitalize="none"
            autoCorrect={false}
          />
        </Card>
      </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  page: { flex: 1 },
  content: { padding: 16, paddingBottom: 64 },
  row: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
  chipRow: { flexDirection: 'row', gap: 8, flexWrap: 'wrap' },
});
