import React, { useState, useEffect, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Alert,
  TextInput,
  ActivityIndicator,
  Modal,
  Platform,
  Image,
  RefreshControl,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import * as ImagePicker from 'expo-image-picker';
import { colors } from '../../src/constants/colors';
import { useAuth } from '../../src/context/AuthContext';
import api from '../../src/services/api';

type TabType = 'profile' | 'branding' | 'legal' | 'api-keys';

interface AppSettings {
  app_name: string;
  logo_base64?: string;
  icon_base64?: string;
  contact_email?: string;
  contact_phone?: string;
  contact_address?: string;
  contact_whatsapp?: string;
  social_facebook?: string;
  social_instagram?: string;
  social_twitter?: string;
  social_youtube?: string;
  social_linkedin?: string;
  hero_title: string;
  hero_subtitle: string;
  hero_cta_text: string;
  about_title: string;
  about_description: string;
  copyright_text: string;
}

interface LegalPage {
  id: string;
  page_type: string;
  title: string;
  content: string;
  is_active: boolean;
}

interface ApiKey {
  id: string;
  name: string;
  key_type: string;
  api_key_masked?: string;
  description?: string;
  is_active: boolean;
}

export default function SettingsScreen() {
  const { user, logout } = useAuth();
  const router = useRouter();
  const [activeTab, setActiveTab] = useState<TabType>('profile');
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [refreshing, setRefreshing] = useState(false);
  
  // App Settings State
  const [appSettings, setAppSettings] = useState<AppSettings>({
    app_name: 'Abbas FIT',
    hero_title: '',
    hero_subtitle: '',
    hero_cta_text: '',
    about_title: '',
    about_description: '',
    copyright_text: '',
  });
  
  // Legal Pages State
  const [legalPages, setLegalPages] = useState<LegalPage[]>([]);
  const [editingLegal, setEditingLegal] = useState<LegalPage | null>(null);
  const [legalModalVisible, setLegalModalVisible] = useState(false);
  
  // API Keys State
  const [apiKeys, setApiKeys] = useState<ApiKey[]>([]);
  const [apiKeyModalVisible, setApiKeyModalVisible] = useState(false);
  const [editingApiKey, setEditingApiKey] = useState<ApiKey | null>(null);
  const [newApiKey, setNewApiKey] = useState({ name: '', key_type: 'custom', api_key: '', description: '' });

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

  const loadData = async () => {
    setLoading(true);
    try {
      await Promise.all([loadAppSettings(), loadLegalPages(), loadApiKeys()]);
    } finally {
      setLoading(false);
    }
  };

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    await loadData();
    setRefreshing(false);
  }, []);

  const loadAppSettings = async () => {
    try {
      const response = await api.get('/admin/settings');
      setAppSettings(response.data);
    } catch (error) {
      console.log('Error loading settings:', error);
    }
  };

  const loadLegalPages = async () => {
    try {
      const response = await api.get('/admin/legal');
      setLegalPages(response.data);
    } catch (error) {
      console.log('Error loading legal pages:', error);
    }
  };

  const loadApiKeys = async () => {
    try {
      const response = await api.get('/admin/api-keys');
      setApiKeys(response.data);
    } catch (error) {
      console.log('Error loading API keys:', error);
    }
  };

  const handleLogout = () => {
    Alert.alert('Logout', 'Are you sure you want to logout?', [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Logout',
        style: 'destructive',
        onPress: async () => {
          await logout();
          router.replace('/');
        },
      },
    ]);
  };

  const saveAppSettings = async () => {
    setSaving(true);
    try {
      await api.put('/admin/settings', appSettings);
      Alert.alert('Success', 'Settings saved successfully!');
    } catch (error) {
      Alert.alert('Error', 'Failed to save settings');
    } finally {
      setSaving(false);
    }
  };

  const pickImage = async (type: 'logo' | 'icon') => {
    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: type === 'logo' ? [3, 1] : [1, 1],
      quality: 0.7,
      base64: true,
    });

    if (!result.canceled && result.assets[0].base64) {
      const base64 = `data:image/jpeg;base64,${result.assets[0].base64}`;
      setAppSettings(prev => ({
        ...prev,
        [type === 'logo' ? 'logo_base64' : 'icon_base64']: base64,
      }));
    }
  };

  const saveLegalPage = async () => {
    if (!editingLegal) return;
    
    setSaving(true);
    try {
      if (editingLegal.id) {
        await api.put(`/admin/legal/${editingLegal.id}`, editingLegal);
      } else {
        await api.post('/admin/legal', editingLegal);
      }
      await loadLegalPages();
      setLegalModalVisible(false);
      setEditingLegal(null);
      Alert.alert('Success', 'Legal page saved!');
    } catch (error) {
      Alert.alert('Error', 'Failed to save legal page');
    } finally {
      setSaving(false);
    }
  };

  const deleteLegalPage = async (id: string) => {
    Alert.alert('Delete', 'Are you sure you want to delete this page?', [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Delete',
        style: 'destructive',
        onPress: async () => {
          try {
            await api.delete(`/admin/legal/${id}`);
            await loadLegalPages();
          } catch (error) {
            Alert.alert('Error', 'Failed to delete');
          }
        },
      },
    ]);
  };

  const saveApiKey = async () => {
    if (!newApiKey.name || !newApiKey.api_key) {
      Alert.alert('Error', 'Please fill in all required fields');
      return;
    }
    
    setSaving(true);
    try {
      if (editingApiKey) {
        await api.put(`/admin/api-keys/${editingApiKey.id}`, newApiKey);
      } else {
        await api.post('/admin/api-keys', newApiKey);
      }
      await loadApiKeys();
      setApiKeyModalVisible(false);
      setEditingApiKey(null);
      setNewApiKey({ name: '', key_type: 'custom', api_key: '', description: '' });
      Alert.alert('Success', 'API key saved!');
    } catch (error) {
      Alert.alert('Error', 'Failed to save API key');
    } finally {
      setSaving(false);
    }
  };

  const deleteApiKey = async (id: string) => {
    Alert.alert('Delete', 'Are you sure you want to delete this API key?', [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Delete',
        style: 'destructive',
        onPress: async () => {
          try {
            await api.delete(`/admin/api-keys/${id}`);
            await loadApiKeys();
          } catch (error) {
            Alert.alert('Error', 'Failed to delete');
          }
        },
      },
    ]);
  };

  const renderProfileTab = () => (
    <View>
      <View style={styles.profileCard}>
        <View style={styles.avatar}>
          <Text style={styles.avatarText}>
            {user?.name?.charAt(0).toUpperCase() || 'A'}
          </Text>
        </View>
        <Text style={styles.profileName}>{user?.name}</Text>
        <Text style={styles.profileEmail}>{user?.email}</Text>
        <View style={styles.roleBadge}>
          <Text style={styles.roleBadgeText}>ADMIN</Text>
        </View>
      </View>

      <View style={styles.section}>
        <Text style={styles.sectionTitle}>Quick Actions</Text>
        <TouchableOpacity style={styles.menuItem} onPress={() => setActiveTab('branding')}>
          <Ionicons name="color-palette-outline" size={22} color={colors.primary} />
          <Text style={styles.menuText}>App Branding & Content</Text>
          <Ionicons name="chevron-forward" size={20} color={colors.textMuted} />
        </TouchableOpacity>
        <TouchableOpacity style={styles.menuItem} onPress={() => setActiveTab('legal')}>
          <Ionicons name="document-text-outline" size={22} color={colors.primary} />
          <Text style={styles.menuText}>Legal Pages</Text>
          <Ionicons name="chevron-forward" size={20} color={colors.textMuted} />
        </TouchableOpacity>
        <TouchableOpacity style={styles.menuItem} onPress={() => setActiveTab('api-keys')}>
          <Ionicons name="key-outline" size={22} color={colors.primary} />
          <Text style={styles.menuText}>API Keys</Text>
          <Ionicons name="chevron-forward" size={20} color={colors.textMuted} />
        </TouchableOpacity>
      </View>

      <TouchableOpacity style={styles.logoutButton} onPress={handleLogout}>
        <Ionicons name="log-out-outline" size={22} color={colors.error} />
        <Text style={styles.logoutText}>Logout</Text>
      </TouchableOpacity>

      <Text style={styles.version}>Abbas FIT v2.0.0</Text>
    </View>
  );

  const renderBrandingTab = () => (
    <View>
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>App Identity</Text>
        
        <Text style={styles.label}>App Name</Text>
        <TextInput
          style={styles.input}
          value={appSettings.app_name}
          onChangeText={(text) => setAppSettings(prev => ({ ...prev, app_name: text }))}
          placeholder="App Name"
          placeholderTextColor={colors.textMuted}
        />

        <Text style={styles.label}>Logo</Text>
        <TouchableOpacity style={styles.imageUpload} onPress={() => pickImage('logo')}>
          {appSettings.logo_base64 ? (
            <Image source={{ uri: appSettings.logo_base64 }} style={styles.previewImage} resizeMode="contain" />
          ) : (
            <>
              <Ionicons name="image-outline" size={32} color={colors.textMuted} />
              <Text style={styles.uploadText}>Tap to upload logo</Text>
            </>
          )}
        </TouchableOpacity>

        <Text style={styles.label}>App Icon</Text>
        <TouchableOpacity style={styles.imageUploadSmall} onPress={() => pickImage('icon')}>
          {appSettings.icon_base64 ? (
            <Image source={{ uri: appSettings.icon_base64 }} style={styles.iconPreview} resizeMode="contain" />
          ) : (
            <Ionicons name="apps-outline" size={32} color={colors.textMuted} />
          )}
        </TouchableOpacity>
      </View>

      <View style={styles.section}>
        <Text style={styles.sectionTitle}>Contact Details</Text>
        
        <Text style={styles.label}>Email</Text>
        <TextInput
          style={styles.input}
          value={appSettings.contact_email || ''}
          onChangeText={(text) => setAppSettings(prev => ({ ...prev, contact_email: text }))}
          placeholder="contact@example.com"
          placeholderTextColor={colors.textMuted}
          keyboardType="email-address"
        />

        <Text style={styles.label}>Phone</Text>
        <TextInput
          style={styles.input}
          value={appSettings.contact_phone || ''}
          onChangeText={(text) => setAppSettings(prev => ({ ...prev, contact_phone: text }))}
          placeholder="+91 98765 43210"
          placeholderTextColor={colors.textMuted}
          keyboardType="phone-pad"
        />

        <Text style={styles.label}>WhatsApp</Text>
        <TextInput
          style={styles.input}
          value={appSettings.contact_whatsapp || ''}
          onChangeText={(text) => setAppSettings(prev => ({ ...prev, contact_whatsapp: text }))}
          placeholder="+91 98765 43210"
          placeholderTextColor={colors.textMuted}
          keyboardType="phone-pad"
        />

        <Text style={styles.label}>Address</Text>
        <TextInput
          style={[styles.input, styles.textArea]}
          value={appSettings.contact_address || ''}
          onChangeText={(text) => setAppSettings(prev => ({ ...prev, contact_address: text }))}
          placeholder="Your business address"
          placeholderTextColor={colors.textMuted}
          multiline
          numberOfLines={3}
        />
      </View>

      <View style={styles.section}>
        <Text style={styles.sectionTitle}>Social Media Links</Text>
        
        {[
          { key: 'social_instagram', label: 'Instagram', icon: 'logo-instagram' },
          { key: 'social_facebook', label: 'Facebook', icon: 'logo-facebook' },
          { key: 'social_youtube', label: 'YouTube', icon: 'logo-youtube' },
          { key: 'social_twitter', label: 'Twitter/X', icon: 'logo-twitter' },
          { key: 'social_linkedin', label: 'LinkedIn', icon: 'logo-linkedin' },
        ].map(item => (
          <View key={item.key} style={styles.socialInput}>
            <Ionicons name={item.icon as any} size={20} color={colors.primary} />
            <TextInput
              style={styles.socialTextInput}
              value={(appSettings as any)[item.key] || ''}
              onChangeText={(text) => setAppSettings(prev => ({ ...prev, [item.key]: text }))}
              placeholder={`${item.label} URL`}
              placeholderTextColor={colors.textMuted}
            />
          </View>
        ))}
      </View>

      <View style={styles.section}>
        <Text style={styles.sectionTitle}>Landing Page Content</Text>
        
        <Text style={styles.label}>Hero Title</Text>
        <TextInput
          style={styles.input}
          value={appSettings.hero_title}
          onChangeText={(text) => setAppSettings(prev => ({ ...prev, hero_title: text }))}
          placeholder="Transform Your Body"
          placeholderTextColor={colors.textMuted}
        />

        <Text style={styles.label}>Hero Subtitle</Text>
        <TextInput
          style={[styles.input, styles.textArea]}
          value={appSettings.hero_subtitle}
          onChangeText={(text) => setAppSettings(prev => ({ ...prev, hero_subtitle: text }))}
          placeholder="Describe your service"
          placeholderTextColor={colors.textMuted}
          multiline
          numberOfLines={2}
        />

        <Text style={styles.label}>CTA Button Text</Text>
        <TextInput
          style={styles.input}
          value={appSettings.hero_cta_text}
          onChangeText={(text) => setAppSettings(prev => ({ ...prev, hero_cta_text: text }))}
          placeholder="Start Your Journey"
          placeholderTextColor={colors.textMuted}
        />

        <Text style={styles.label}>About Title</Text>
        <TextInput
          style={styles.input}
          value={appSettings.about_title}
          onChangeText={(text) => setAppSettings(prev => ({ ...prev, about_title: text }))}
          placeholder="About Us"
          placeholderTextColor={colors.textMuted}
        />

        <Text style={styles.label}>About Description</Text>
        <TextInput
          style={[styles.input, styles.textArea]}
          value={appSettings.about_description}
          onChangeText={(text) => setAppSettings(prev => ({ ...prev, about_description: text }))}
          placeholder="Tell about your business"
          placeholderTextColor={colors.textMuted}
          multiline
          numberOfLines={4}
        />

        <Text style={styles.label}>Copyright Text</Text>
        <TextInput
          style={styles.input}
          value={appSettings.copyright_text}
          onChangeText={(text) => setAppSettings(prev => ({ ...prev, copyright_text: text }))}
          placeholder="© 2025 Your Company"
          placeholderTextColor={colors.textMuted}
        />
      </View>

      <TouchableOpacity style={styles.saveButton} onPress={saveAppSettings} disabled={saving}>
        {saving ? (
          <ActivityIndicator color={colors.text} />
        ) : (
          <>
            <Ionicons name="save-outline" size={20} color={colors.text} />
            <Text style={styles.saveButtonText}>Save Settings</Text>
          </>
        )}
      </TouchableOpacity>
    </View>
  );

  const renderLegalTab = () => (
    <View>
      <TouchableOpacity 
        style={styles.addButton}
        onPress={() => {
          setEditingLegal({ id: '', page_type: 'terms', title: '', content: '', is_active: true });
          setLegalModalVisible(true);
        }}
      >
        <Ionicons name="add" size={24} color={colors.text} />
        <Text style={styles.addButtonText}>Add Legal Page</Text>
      </TouchableOpacity>

      {legalPages.map(page => (
        <View key={page.id} style={styles.legalCard}>
          <View style={styles.legalCardHeader}>
            <View style={styles.legalCardInfo}>
              <Text style={styles.legalCardTitle}>{page.title}</Text>
              <Text style={styles.legalCardType}>{page.page_type.toUpperCase()}</Text>
            </View>
            <View style={styles.legalCardActions}>
              <TouchableOpacity
                style={styles.iconButton}
                onPress={() => {
                  setEditingLegal(page);
                  setLegalModalVisible(true);
                }}
              >
                <Ionicons name="create-outline" size={20} color={colors.primary} />
              </TouchableOpacity>
              <TouchableOpacity
                style={styles.iconButton}
                onPress={() => deleteLegalPage(page.id)}
              >
                <Ionicons name="trash-outline" size={20} color={colors.error} />
              </TouchableOpacity>
            </View>
          </View>
          <Text style={styles.legalPreview} numberOfLines={2}>
            {page.content.replace(/<[^>]*>/g, '').substring(0, 100)}...
          </Text>
        </View>
      ))}

      {legalPages.length === 0 && (
        <View style={styles.emptyState}>
          <Ionicons name="document-text-outline" size={48} color={colors.textMuted} />
          <Text style={styles.emptyText}>No legal pages yet</Text>
          <Text style={styles.emptySubtext}>Add Terms, Privacy Policy, etc.</Text>
        </View>
      )}
    </View>
  );

  const renderApiKeysTab = () => (
    <View>
      <TouchableOpacity 
        style={styles.addButton}
        onPress={() => {
          setEditingApiKey(null);
          setNewApiKey({ name: '', key_type: 'custom', api_key: '', description: '' });
          setApiKeyModalVisible(true);
        }}
      >
        <Ionicons name="add" size={24} color={colors.text} />
        <Text style={styles.addButtonText}>Add API Key</Text>
      </TouchableOpacity>

      {apiKeys.map(key => (
        <View key={key.id} style={styles.apiKeyCard}>
          <View style={styles.apiKeyHeader}>
            <View style={styles.apiKeyInfo}>
              <Ionicons name="key" size={20} color={colors.primary} />
              <Text style={styles.apiKeyName}>{key.name}</Text>
            </View>
            <View style={[styles.statusBadge, key.is_active ? styles.activeBadge : styles.inactiveBadge]}>
              <Text style={styles.statusText}>{key.is_active ? 'Active' : 'Inactive'}</Text>
            </View>
          </View>
          <Text style={styles.apiKeyType}>{key.key_type.toUpperCase()}</Text>
          <Text style={styles.apiKeyMasked}>{key.api_key_masked || '••••••••'}</Text>
          {key.description && <Text style={styles.apiKeyDesc}>{key.description}</Text>}
          <View style={styles.apiKeyActions}>
            <TouchableOpacity
              style={styles.smallButton}
              onPress={() => {
                setEditingApiKey(key);
                setNewApiKey({ name: key.name, key_type: key.key_type, api_key: '', description: key.description || '' });
                setApiKeyModalVisible(true);
              }}
            >
              <Text style={styles.smallButtonText}>Edit</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={[styles.smallButton, styles.deleteButton]}
              onPress={() => deleteApiKey(key.id)}
            >
              <Text style={styles.smallButtonTextDanger}>Delete</Text>
            </TouchableOpacity>
          </View>
        </View>
      ))}

      {apiKeys.length === 0 && (
        <View style={styles.emptyState}>
          <Ionicons name="key-outline" size={48} color={colors.textMuted} />
          <Text style={styles.emptyText}>No API keys configured</Text>
          <Text style={styles.emptySubtext}>Add Gemini, OpenAI, or other API keys</Text>
        </View>
      )}
    </View>
  );

  const tabs = [
    { id: 'profile', label: 'Profile', icon: 'person-outline' },
    { id: 'branding', label: 'Branding', icon: 'color-palette-outline' },
    { id: 'legal', label: 'Legal', icon: 'document-outline' },
    { id: 'api-keys', label: 'API Keys', icon: 'key-outline' },
  ];

  return (
    <SafeAreaView style={styles.container} edges={['top']}>
      <View style={styles.header}>
        <Text style={styles.title}>Settings</Text>
      </View>

      <View style={styles.tabBar}>
        {tabs.map(tab => (
          <TouchableOpacity
            key={tab.id}
            style={[styles.tab, activeTab === tab.id && styles.tabActive]}
            onPress={() => setActiveTab(tab.id as TabType)}
          >
            <Ionicons
              name={tab.icon as any}
              size={18}
              color={activeTab === tab.id ? colors.primary : colors.textMuted}
            />
            <Text style={[styles.tabText, activeTab === tab.id && styles.tabTextActive]}>
              {tab.label}
            </Text>
          </TouchableOpacity>
        ))}
      </View>

      {loading ? (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={colors.primary} />
        </View>
      ) : (
        <ScrollView 
          style={styles.content}
          refreshControl={
            <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={colors.primary} />
          }
        >
          {activeTab === 'profile' && renderProfileTab()}
          {activeTab === 'branding' && renderBrandingTab()}
          {activeTab === 'legal' && renderLegalTab()}
          {activeTab === 'api-keys' && renderApiKeysTab()}
          <View style={{ height: 40 }} />
        </ScrollView>
      )}

      {/* Legal Page Modal */}
      <Modal visible={legalModalVisible} animationType="slide" presentationStyle="pageSheet">
        <SafeAreaView style={styles.modalContainer}>
          <View style={styles.modalHeader}>
            <TouchableOpacity onPress={() => setLegalModalVisible(false)}>
              <Text style={styles.modalCancel}>Cancel</Text>
            </TouchableOpacity>
            <Text style={styles.modalTitle}>{editingLegal?.id ? 'Edit' : 'New'} Legal Page</Text>
            <TouchableOpacity onPress={saveLegalPage} disabled={saving}>
              {saving ? (
                <ActivityIndicator size="small" color={colors.primary} />
              ) : (
                <Text style={styles.modalSave}>Save</Text>
              )}
            </TouchableOpacity>
          </View>
          <ScrollView style={styles.modalContent}>
            <Text style={styles.label}>Page Type</Text>
            <View style={styles.typeSelector}>
              {['terms', 'privacy', 'refund', 'disclaimer'].map(type => (
                <TouchableOpacity
                  key={type}
                  style={[styles.typeOption, editingLegal?.page_type === type && styles.typeOptionActive]}
                  onPress={() => setEditingLegal(prev => prev ? { ...prev, page_type: type } : null)}
                >
                  <Text style={[styles.typeOptionText, editingLegal?.page_type === type && styles.typeOptionTextActive]}>
                    {type.charAt(0).toUpperCase() + type.slice(1)}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>

            <Text style={styles.label}>Title</Text>
            <TextInput
              style={styles.input}
              value={editingLegal?.title || ''}
              onChangeText={(text) => setEditingLegal(prev => prev ? { ...prev, title: text } : null)}
              placeholder="Terms and Conditions"
              placeholderTextColor={colors.textMuted}
            />

            <Text style={styles.label}>Content (HTML supported)</Text>
            <TextInput
              style={[styles.input, styles.textAreaLarge]}
              value={editingLegal?.content || ''}
              onChangeText={(text) => setEditingLegal(prev => prev ? { ...prev, content: text } : null)}
              placeholder="Enter your legal content here..."
              placeholderTextColor={colors.textMuted}
              multiline
              textAlignVertical="top"
            />
          </ScrollView>
        </SafeAreaView>
      </Modal>

      {/* API Key Modal */}
      <Modal visible={apiKeyModalVisible} animationType="slide" presentationStyle="pageSheet">
        <SafeAreaView style={styles.modalContainer}>
          <View style={styles.modalHeader}>
            <TouchableOpacity onPress={() => setApiKeyModalVisible(false)}>
              <Text style={styles.modalCancel}>Cancel</Text>
            </TouchableOpacity>
            <Text style={styles.modalTitle}>{editingApiKey ? 'Edit' : 'New'} API Key</Text>
            <TouchableOpacity onPress={saveApiKey} disabled={saving}>
              {saving ? (
                <ActivityIndicator size="small" color={colors.primary} />
              ) : (
                <Text style={styles.modalSave}>Save</Text>
              )}
            </TouchableOpacity>
          </View>
          <ScrollView style={styles.modalContent}>
            <Text style={styles.label}>Key Name *</Text>
            <TextInput
              style={styles.input}
              value={newApiKey.name}
              onChangeText={(text) => setNewApiKey(prev => ({ ...prev, name: text }))}
              placeholder="e.g., Gemini API Key"
              placeholderTextColor={colors.textMuted}
            />

            <Text style={styles.label}>Key Type</Text>
            <View style={styles.typeSelector}>
              {['gemini', 'openai', 'stripe', 'sendgrid', 'custom'].map(type => (
                <TouchableOpacity
                  key={type}
                  style={[styles.typeOption, newApiKey.key_type === type && styles.typeOptionActive]}
                  onPress={() => setNewApiKey(prev => ({ ...prev, key_type: type }))}
                >
                  <Text style={[styles.typeOptionText, newApiKey.key_type === type && styles.typeOptionTextActive]}>
                    {type.charAt(0).toUpperCase() + type.slice(1)}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>

            <Text style={styles.label}>API Key *</Text>
            <TextInput
              style={styles.input}
              value={newApiKey.api_key}
              onChangeText={(text) => setNewApiKey(prev => ({ ...prev, api_key: text }))}
              placeholder={editingApiKey ? 'Leave blank to keep existing' : 'Enter API key'}
              placeholderTextColor={colors.textMuted}
              secureTextEntry
            />

            <Text style={styles.label}>Description</Text>
            <TextInput
              style={[styles.input, styles.textArea]}
              value={newApiKey.description}
              onChangeText={(text) => setNewApiKey(prev => ({ ...prev, description: text }))}
              placeholder="What is this key used for?"
              placeholderTextColor={colors.textMuted}
              multiline
              numberOfLines={3}
            />
          </ScrollView>
        </SafeAreaView>
      </Modal>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  header: {
    padding: 20,
    paddingBottom: 12,
  },
  title: {
    fontSize: 28,
    fontWeight: '700',
    color: colors.text,
  },
  tabBar: {
    flexDirection: 'row',
    paddingHorizontal: 16,
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
    marginBottom: 8,
  },
  tab: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 12,
    gap: 4,
  },
  tabActive: {
    borderBottomWidth: 2,
    borderBottomColor: colors.primary,
  },
  tabText: {
    fontSize: 12,
    color: colors.textMuted,
    fontWeight: '500',
  },
  tabTextActive: {
    color: colors.primary,
    fontWeight: '600',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  content: {
    flex: 1,
    padding: 20,
    paddingTop: 8,
  },
  profileCard: {
    backgroundColor: colors.backgroundCard,
    borderRadius: 16,
    padding: 24,
    alignItems: 'center',
    marginBottom: 24,
  },
  avatar: {
    width: 80,
    height: 80,
    borderRadius: 40,
    backgroundColor: colors.primary,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 12,
  },
  avatarText: {
    fontSize: 32,
    fontWeight: '700',
    color: colors.text,
  },
  profileName: {
    fontSize: 20,
    fontWeight: '700',
    color: colors.text,
    marginBottom: 4,
  },
  profileEmail: {
    fontSize: 14,
    color: colors.textSecondary,
    marginBottom: 12,
  },
  roleBadge: {
    backgroundColor: colors.primary,
    paddingHorizontal: 12,
    paddingVertical: 4,
    borderRadius: 8,
  },
  roleBadgeText: {
    fontSize: 12,
    fontWeight: '700',
    color: colors.text,
  },
  section: {
    marginBottom: 24,
  },
  sectionTitle: {
    fontSize: 14,
    fontWeight: '600',
    color: colors.textMuted,
    marginBottom: 12,
    textTransform: 'uppercase',
    letterSpacing: 1,
  },
  menuItem: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.backgroundCard,
    padding: 16,
    borderRadius: 12,
    marginBottom: 8,
  },
  menuText: {
    flex: 1,
    fontSize: 16,
    color: colors.text,
    marginLeft: 12,
  },
  logoutButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'rgba(239, 68, 68, 0.1)',
    padding: 16,
    borderRadius: 12,
    gap: 8,
    marginTop: 12,
  },
  logoutText: {
    fontSize: 16,
    fontWeight: '600',
    color: colors.error,
  },
  version: {
    textAlign: 'center',
    fontSize: 12,
    color: colors.textMuted,
    marginTop: 24,
    marginBottom: 24,
  },
  label: {
    fontSize: 14,
    fontWeight: '600',
    color: colors.textSecondary,
    marginBottom: 8,
    marginTop: 12,
  },
  input: {
    backgroundColor: colors.backgroundCard,
    borderRadius: 12,
    padding: 16,
    fontSize: 16,
    color: colors.text,
    borderWidth: 1,
    borderColor: colors.border,
  },
  textArea: {
    minHeight: 80,
    textAlignVertical: 'top',
  },
  textAreaLarge: {
    minHeight: 300,
    textAlignVertical: 'top',
  },
  imageUpload: {
    backgroundColor: colors.backgroundCard,
    borderRadius: 12,
    padding: 32,
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 2,
    borderColor: colors.border,
    borderStyle: 'dashed',
    minHeight: 120,
  },
  imageUploadSmall: {
    backgroundColor: colors.backgroundCard,
    borderRadius: 12,
    width: 80,
    height: 80,
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 2,
    borderColor: colors.border,
    borderStyle: 'dashed',
  },
  previewImage: {
    width: '100%',
    height: 80,
  },
  iconPreview: {
    width: 60,
    height: 60,
    borderRadius: 12,
  },
  uploadText: {
    fontSize: 14,
    color: colors.textMuted,
    marginTop: 8,
  },
  socialInput: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.backgroundCard,
    borderRadius: 12,
    paddingLeft: 16,
    marginBottom: 8,
    borderWidth: 1,
    borderColor: colors.border,
  },
  socialTextInput: {
    flex: 1,
    padding: 16,
    fontSize: 16,
    color: colors.text,
  },
  saveButton: {
    backgroundColor: colors.primary,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 16,
    borderRadius: 12,
    gap: 8,
    marginTop: 16,
  },
  saveButtonText: {
    fontSize: 16,
    fontWeight: '600',
    color: colors.text,
  },
  addButton: {
    backgroundColor: colors.primary,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 16,
    borderRadius: 12,
    gap: 8,
    marginBottom: 16,
  },
  addButtonText: {
    fontSize: 16,
    fontWeight: '600',
    color: colors.text,
  },
  legalCard: {
    backgroundColor: colors.backgroundCard,
    borderRadius: 12,
    padding: 16,
    marginBottom: 12,
  },
  legalCardHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    marginBottom: 8,
  },
  legalCardInfo: {
    flex: 1,
  },
  legalCardTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: colors.text,
    marginBottom: 4,
  },
  legalCardType: {
    fontSize: 12,
    color: colors.primary,
    fontWeight: '500',
  },
  legalCardActions: {
    flexDirection: 'row',
    gap: 8,
  },
  iconButton: {
    padding: 8,
    backgroundColor: colors.background,
    borderRadius: 8,
  },
  legalPreview: {
    fontSize: 14,
    color: colors.textMuted,
    lineHeight: 20,
  },
  apiKeyCard: {
    backgroundColor: colors.backgroundCard,
    borderRadius: 12,
    padding: 16,
    marginBottom: 12,
  },
  apiKeyHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 8,
  },
  apiKeyInfo: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
  },
  apiKeyName: {
    fontSize: 16,
    fontWeight: '600',
    color: colors.text,
  },
  statusBadge: {
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 6,
  },
  activeBadge: {
    backgroundColor: 'rgba(34, 197, 94, 0.2)',
  },
  inactiveBadge: {
    backgroundColor: 'rgba(239, 68, 68, 0.2)',
  },
  statusText: {
    fontSize: 12,
    fontWeight: '500',
    color: colors.text,
  },
  apiKeyType: {
    fontSize: 12,
    color: colors.primary,
    fontWeight: '500',
    marginBottom: 4,
  },
  apiKeyMasked: {
    fontSize: 14,
    color: colors.textMuted,
    fontFamily: Platform.OS === 'ios' ? 'Menlo' : 'monospace',
    marginBottom: 4,
  },
  apiKeyDesc: {
    fontSize: 14,
    color: colors.textSecondary,
    marginBottom: 8,
  },
  apiKeyActions: {
    flexDirection: 'row',
    gap: 8,
    marginTop: 8,
  },
  smallButton: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    backgroundColor: colors.background,
    borderRadius: 8,
  },
  deleteButton: {
    backgroundColor: 'rgba(239, 68, 68, 0.1)',
  },
  smallButtonText: {
    fontSize: 14,
    color: colors.primary,
    fontWeight: '500',
  },
  smallButtonTextDanger: {
    fontSize: 14,
    color: colors.error,
    fontWeight: '500',
  },
  emptyState: {
    alignItems: 'center',
    padding: 40,
  },
  emptyText: {
    fontSize: 18,
    fontWeight: '600',
    color: colors.text,
    marginTop: 16,
  },
  emptySubtext: {
    fontSize: 14,
    color: colors.textMuted,
    marginTop: 4,
  },
  modalContainer: {
    flex: 1,
    backgroundColor: colors.background,
  },
  modalHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: colors.text,
  },
  modalCancel: {
    fontSize: 16,
    color: colors.textMuted,
  },
  modalSave: {
    fontSize: 16,
    fontWeight: '600',
    color: colors.primary,
  },
  modalContent: {
    flex: 1,
    padding: 20,
  },
  typeSelector: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 8,
  },
  typeOption: {
    paddingHorizontal: 16,
    paddingVertical: 10,
    backgroundColor: colors.backgroundCard,
    borderRadius: 8,
    borderWidth: 1,
    borderColor: colors.border,
  },
  typeOptionActive: {
    backgroundColor: colors.primary,
    borderColor: colors.primary,
  },
  typeOptionText: {
    fontSize: 14,
    color: colors.textMuted,
  },
  typeOptionTextActive: {
    color: colors.text,
    fontWeight: '600',
  },
});
