import React, { useState } from 'react';
import { View, TextInput, Button, Text, StyleSheet, ScrollView, SafeAreaView, ActivityIndicator, KeyboardAvoidingView, Platform } from 'react-native';
import { executeSql } from '@/lib/db';
import { ThemedView } from '@/components/ThemedView';
import { ThemedText } from '@/components/ThemedText';

const DebugScreen = () => {
    const [sql, setSql] = useState('SELECT * FROM upload_tasks;');
    const [results, setResults] = useState<any>(null);
    const [loading, setLoading] = useState(false);

    const handleExecuteSql = async (query: string) => {
        if (!query) return;
        setLoading(true);
        setResults(null);
        try {
            const result = await executeSql(query);
            setResults(result);
        } catch (error) {
            setResults({ error: (error as Error).message });
        } finally {
            setLoading(false);
        }
    };

    const presetQueries = [
        { title: 'All Uploads', query: 'SELECT * FROM upload_tasks;' },
        { title: 'Delete All Uploads', query: 'DELETE FROM upload_tasks;' },
        { title: 'Show Tables', query: "SELECT name FROM sqlite_master WHERE type='table';" },
    ];

    return (
        <ThemedView style={styles.container}>
            <SafeAreaView style={styles.safeArea}>
                <KeyboardAvoidingView 
                    behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
                    style={styles.keyboardAvoidingView}
                >
                    <ThemedText type="title" style={styles.title}>SQL Debugger</ThemedText>
                    <View style={styles.inputContainer}>
                        <TextInput
                            style={styles.input}
                            onChangeText={setSql}
                            value={sql}
                            placeholder="Enter SQL query"
                            multiline
                            autoCapitalize='none'
                            autoCorrect={false}
                        />
                        <Button title="Execute" onPress={() => handleExecuteSql(sql)} disabled={loading} />
                    </View>
                    <View style={styles.presetsContainer}>
                        {presetQueries.map((item, index) => (
                            <View key={index} style={styles.presetButton}>
                                <Button title={item.title} onPress={() => {
                                    setSql(item.query);
                                    handleExecuteSql(item.query);
                                }} disabled={loading} />
                            </View>
                        ))}
                    </View>
                    <ThemedText type="subtitle" style={styles.resultTitle}>Results:</ThemedText>
                    <ScrollView style={styles.resultsContainer}>
                        {loading ? (
                            <ActivityIndicator size="large" />
                        ) : (
                            <Text selectable style={styles.resultsText}>
                                {results ? JSON.stringify(results, null, 2) : 'No results yet.'}
                            </Text>
                        )}
                    </ScrollView>
                </KeyboardAvoidingView>
            </SafeAreaView>
        </ThemedView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    safeArea: {
        flex: 1,
    },
    keyboardAvoidingView: {
        flex: 1,
        padding: 15,
    },
    title: {
        marginBottom: 15,
        textAlign: 'center',
    },
    inputContainer: {
        marginBottom: 10,
    },
    input: {
        borderWidth: 1,
        borderColor: '#ccc',
        padding: 10,
        marginBottom: 10,
        minHeight: 100,
        textAlignVertical: 'top',
        backgroundColor: 'white',
        fontSize: 16,
    },
    presetsContainer: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        justifyContent: 'flex-start',
        marginBottom: 15,
    },
    presetButton: {
        marginRight: 10,
        marginBottom: 10,
    },
    resultTitle: {
        marginBottom: 5,
    },
    resultsContainer: {
        flex: 1,
        borderWidth: 1,
        borderColor: '#ccc',
        padding: 10,
        backgroundColor: '#f5f5f5',
    },
    resultsText: {
        fontFamily: Platform.OS === 'ios' ? 'Menlo' : 'monospace',
        color: '#333',
    },
});

export default DebugScreen;
