import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, ScrollView, Switch, Alert, Share, TouchableOpacity } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { RootStackParamList } from '../navigation/types';
import { getSettings, updateSettings, getAllProjects, getStepsByProject, getListItems } from '../lib/db/repositories';
import { Settings } from '../types';
import { Card, Button } from '../components';
import { colors, spacing, typography, borderRadius } from '../lib/theme';
import { useAuth } from '../contexts/AuthContext';

type NavigationProp = NativeStackNavigationProp<RootStackParamList>;

export const SettingsScreen: React.FC = () => {
  const navigation = useNavigation<NavigationProp>();
  const { user, signOut } = useAuth();
  const [settings, setSettings] = useState<Settings>({
    unitSystem: 'imperial',
    tempUnit: 'F',
    weightUnit: 'lb',
    analyticsOptIn: false,
  });

  useEffect(() => {
    if (user) {
      loadSettings();
    }
  }, [user]);

  const loadSettings = async () => {
    if (!user) return;
    try {
      const current = await getSettings(user.id);
      console.log('Loaded settings:', current);
      setSettings(current);
    } catch (error) {
      console.error('Failed to load settings:', error);
    }
  };

  const handleToggle = async (key: keyof Settings, value: any) => {
    if (!user) return;
    try {
      const updated = { ...settings, [key]: value };
      console.log('Updating settings:', key, '=', value, 'Full settings:', updated);
      setSettings(updated);
      await updateSettings(user.id, updated);
      console.log('Settings saved successfully');
    } catch (error) {
      console.error('Failed to save settings:', error);
      Alert.alert('Error', 'Failed to save settings');
    }
  };

  const handleExportData = async () => {
    if (!user) return;

    try {
      const projects = await getAllProjects(user.id);
      const shoppingList = await getListItems(user.id, 'shopping');
      const wishList = await getListItems(user.id, 'wish');

      const exportData: any = {
        exportDate: new Date().toISOString(),
        version: '1.0.0',
        projects: [],
        shoppingList,
        wishList,
      };

      for (const project of projects) {
        const steps = await getStepsByProject(project.id);
        exportData.projects.push({
          ...project,
          steps,
        });
      }

      const jsonString = JSON.stringify(exportData, null, 2);

      // Share the JSON data
      await Share.share({
        message: jsonString,
        title: 'Pottery Diary Export',
      });

      Alert.alert('Success', 'Data exported successfully');
    } catch (error) {
      console.error('Export failed:', error);
      Alert.alert('Error', 'Failed to export data');
    }
  };

  const handleLogout = () => {
    Alert.alert(
      'Logout',
      'Are you sure you want to logout?',
      [
        { text: 'Cancel', style: 'cancel' },
        {
          text: 'Logout',
          style: 'destructive',
          onPress: async () => {
            try {
              await signOut();
            } catch (error) {
              console.error('Logout failed:', error);
              Alert.alert('Error', 'Failed to logout');
            }
          },
        },
      ]
    );
  };

  return (
    <SafeAreaView style={styles.safeArea} edges={['top']}>
      <ScrollView style={styles.container} contentContainerStyle={styles.content}>
        <Card>
          <Text style={styles.sectionTitle}>Units</Text>

          <View style={styles.setting}>
            <View style={styles.settingHeader}>
              <Text style={styles.settingLabel}>Temperature Unit</Text>
            </View>
            <View style={styles.toggleContainer}>
              <TouchableOpacity
                style={[styles.toggleButton, settings.tempUnit === 'F' && styles.toggleButtonActive]}
                onPress={() => handleToggle('tempUnit', 'F')}
              >
                <Text style={[styles.toggleText, settings.tempUnit === 'F' && styles.toggleTextActive]}>°F</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={[styles.toggleButton, settings.tempUnit === 'C' && styles.toggleButtonActive]}
                onPress={() => handleToggle('tempUnit', 'C')}
              >
                <Text style={[styles.toggleText, settings.tempUnit === 'C' && styles.toggleTextActive]}>°C</Text>
              </TouchableOpacity>
            </View>
          </View>

          <View style={styles.setting}>
            <View style={styles.settingHeader}>
              <Text style={styles.settingLabel}>Unit System</Text>
            </View>
            <View style={styles.toggleContainer}>
              <TouchableOpacity
                style={[styles.toggleButton, settings.unitSystem === 'imperial' && styles.toggleButtonActive]}
                onPress={() => handleToggle('unitSystem', 'imperial')}
              >
                <Text style={[styles.toggleText, settings.unitSystem === 'imperial' && styles.toggleTextActive]}>Imperial</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={[styles.toggleButton, settings.unitSystem === 'metric' && styles.toggleButtonActive]}
                onPress={() => handleToggle('unitSystem', 'metric')}
              >
                <Text style={[styles.toggleText, settings.unitSystem === 'metric' && styles.toggleTextActive]}>Metric</Text>
              </TouchableOpacity>
            </View>
          </View>

          <View style={[styles.setting, styles.noBorder]}>
            <View style={styles.settingHeader}>
              <Text style={styles.settingLabel}>Weight Unit</Text>
            </View>
            <View style={styles.toggleContainer}>
              <TouchableOpacity
                style={[styles.toggleButton, (settings.weightUnit === 'lb' || settings.weightUnit === 'oz') && styles.toggleButtonActive]}
                onPress={() => handleToggle('weightUnit', 'lb')}
              >
                <Text style={[styles.toggleText, (settings.weightUnit === 'lb' || settings.weightUnit === 'oz') && styles.toggleTextActive]}>lb</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={[styles.toggleButton, (settings.weightUnit === 'kg' || settings.weightUnit === 'g') && styles.toggleButtonActive]}
                onPress={() => handleToggle('weightUnit', 'kg')}
              >
                <Text style={[styles.toggleText, (settings.weightUnit === 'kg' || settings.weightUnit === 'g') && styles.toggleTextActive]}>kg</Text>
              </TouchableOpacity>
            </View>
          </View>
        </Card>

        <Card style={styles.card}>
          <Text style={styles.sectionTitle}>My Lists</Text>

          <Button
            title="Shopping List"
            onPress={() => navigation.navigate('UserList', { type: 'shopping' })}
            variant="outline"
          />

          <Button
            title="Wish List"
            onPress={() => navigation.navigate('UserList', { type: 'wish' })}
            variant="outline"
            style={styles.listButton}
          />

          <Text style={styles.exportNote}>
            Keep track of supplies you need to buy or items you want to acquire
          </Text>
        </Card>

        <Card style={styles.card}>
          <Text style={styles.sectionTitle}>Data</Text>

          <Button
            title="Export All Data (JSON)"
            onPress={handleExportData}
            variant="outline"
          />

          <Text style={styles.exportNote}>
            Export all your projects and steps as JSON for backup or sharing
          </Text>
        </Card>

        <Card style={styles.card}>
          <Text style={styles.sectionTitle}>Account</Text>

          {user && (
            <View style={styles.infoRow}>
              <Text style={styles.infoLabel}>Logged in as</Text>
              <Text style={styles.infoValue}>{user.name}</Text>
            </View>
          )}

          {user && (
            <View style={[styles.infoRow, styles.noBorder]}>
              <Text style={styles.infoLabel}>Email</Text>
              <Text style={styles.infoValue}>{user.email}</Text>
            </View>
          )}

          <Button
            title="Logout"
            onPress={handleLogout}
            variant="outline"
            style={styles.logoutButton}
          />
        </Card>

        <Card style={styles.card}>
          <Text style={styles.sectionTitle}>About</Text>

          <View style={styles.infoRow}>
            <Text style={styles.infoLabel}>Version</Text>
            <Text style={styles.infoValue}>1.0.0</Text>
          </View>

          <View style={[styles.infoRow, styles.noBorder]}>
            <Text style={styles.infoLabel}>Developer</Text>
            <Text style={styles.infoValue}>Made with ❤️ for makers</Text>
          </View>
        </Card>

        <View style={styles.footer}>
          <Text style={styles.footerText}>🏺 Pottery Diary</Text>
          <Text style={styles.footerText}>Keep track of your ceramic journey</Text>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: colors.backgroundSecondary,
  },
  container: {
    flex: 1,
  },
  content: {
    paddingHorizontal: spacing.md,
    paddingTop: spacing.xl,
    paddingBottom: 100, // Extra space for floating tab bar
  },
  card: {
    marginTop: spacing.md,
  },
  sectionTitle: {
    fontSize: typography.fontSize.lg,
    fontWeight: typography.fontWeight.bold,
    color: colors.text,
    marginBottom: spacing.md,
    letterSpacing: 0.5,
  },
  setting: {
    flexDirection: 'column',
    alignItems: 'flex-start',
    paddingVertical: spacing.md,
    borderBottomWidth: 2,
    borderBottomColor: colors.border,
  },
  settingLabel: {
    fontSize: typography.fontSize.md,
    fontWeight: typography.fontWeight.medium,
    color: colors.text,
  },
  settingValue: {
    fontSize: typography.fontSize.sm,
    marginTop: spacing.xs,
  },
  settingHeader: {
    marginBottom: spacing.sm,
    width: '100%',
  },
  settingInfo: {
    flex: 1,
    paddingRight: spacing.sm,
  },
  infoRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: spacing.md,
    borderBottomWidth: 2,
    borderBottomColor: colors.border,
  },
  infoLabel: {
    fontSize: typography.fontSize.md,
    fontWeight: typography.fontWeight.bold,
    color: colors.text,
    letterSpacing: 0.3,
  },
  infoValue: {
    fontSize: typography.fontSize.sm,
    color: colors.textSecondary,
  },
  footer: {
    alignItems: 'center',
    marginTop: spacing.xl,
    paddingVertical: spacing.lg,
  },
  footerText: {
    fontSize: typography.fontSize.sm,
    color: colors.textSecondary,
    textAlign: 'center',
    marginBottom: spacing.xs,
  },
  exportNote: {
    fontSize: typography.fontSize.sm,
    color: colors.textSecondary,
    marginTop: spacing.md,
    fontStyle: 'italic',
  },
  logoutButton: {
    marginTop: spacing.md,
  },
  listButton: {
    marginTop: spacing.sm,
  },
  toggleContainer: {
    flexDirection: 'row',
    backgroundColor: colors.background,
    borderRadius: borderRadius.md,
    padding: 0,
    borderWidth: 1,
    borderColor: colors.border,
    width: '100%',
    overflow: 'hidden',
  },
  toggleButton: {
    flex: 1,
    alignItems: 'center',
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.sm,
    borderRadius: borderRadius.md,
  },
  toggleButtonActive: {
    backgroundColor: colors.primary,
  },
  toggleText: {
    fontSize: typography.fontSize.sm,
    color: colors.textSecondary,
    fontWeight: typography.fontWeight.medium,
  },
  toggleTextActive: {
    color: colors.buttonText,
    fontWeight: typography.fontWeight.bold,
  },
  noBorder: {
    borderBottomWidth: 0,
  },
});
