import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Alert } from 'react-native';
import { useRouter } from 'expo-router';
import { withObservables } from '@nozbe/watermelondb/react';
import { database } from '../../src/db';
import UserChallenge from '../../src/db/models/UserChallenge';
import { Q } from '@nozbe/watermelondb';
import ProgressScreen from '../screens/ProgressScreen';
import { Colors } from '@/constants/theme';

const HomeScreen = ({ userChallenge }: { userChallenge: UserChallenge | null }) => {
  const router = useRouter();

  const handleReset = async () => {
    Alert.alert(
      "Reset Data",
      "Are you sure you want to clear all local data? This cannot be undone.",
      [
        { text: "Cancel", style: "cancel" },
        { 
          text: "Reset", 
          style: "destructive", 
          onPress: async () => {
            try {
              await database.write(async () => {
                await database.unsafeResetDatabase();
              });
              // Reload or just let the UI update (observables should handle it, but reset might need reload)
              // For now, unsafeResetDatabase might require app reload in some contexts, 
              // but let's see if observables pick up the empty state.
              // Actually, unsafeResetDatabase clears everything.
            } catch (e) {
              console.error("Error resetting database:", e);
            }
          }
        }
      ]
    );
  };

  if (userChallenge) {
    return (
      <View style={styles.container}>
        <ProgressScreen />
        <TouchableOpacity style={styles.debugButton} onPress={handleReset}>
            <Text style={styles.debugButtonText}>Debug: Reset Data</Text>
        </TouchableOpacity>
      </View>
    );
  }

  return (
    <View style={styles.emptyContainer}>
      <Text style={styles.title}>Welcome to Surge</Text>
      <Text style={styles.subtitle}>You don{`'`}t have an active challenge yet.</Text>
      
      <TouchableOpacity 
        style={styles.button}
        onPress={() => router.push('/(tabs)/explore')}
      >
        <Text style={styles.buttonText}>Explore Challenges</Text>
      </TouchableOpacity>

      <TouchableOpacity style={styles.debugButton} onPress={handleReset}>
            <Text style={styles.debugButtonText}>Debug: Reset Data</Text>
      </TouchableOpacity>
    </View>
  );
};

const enhance = withObservables([], () => ({
  userChallenge: database.get<UserChallenge>('user_challenges')
    .query(Q.where('status', 'active'))
    .observeWithColumns(['status'])
    .pipe(
      // @ts-ignore
      require('rxjs/operators').map((challenges: UserChallenge[]) => challenges.length > 0 ? challenges[0] : null)
    ),
}));

export default enhance(HomeScreen);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
    backgroundColor: '#f5f5f5',
  },
  title: {
    fontSize: 32,
    fontWeight: 'bold',
    marginBottom: 10,
    color: '#333',
  },
  subtitle: {
    fontSize: 18,
    color: '#666',
    marginBottom: 40,
    textAlign: 'center',
  },
  button: {
    backgroundColor: Colors.light.tint,
    paddingHorizontal: 30,
    paddingVertical: 15,
    borderRadius: 25,
    marginBottom: 20,
  },
  buttonText: {
    color: 'white',
    fontSize: 18,
    fontWeight: 'bold',
  },
  debugButton: {
    marginTop: 20,
    padding: 10,
  },
  debugButtonText: {
    color: 'red',
    fontSize: 14,
  }
});
