import React, { useState } from 'react';
import { View, StyleSheet } from 'react-native';
import { Button, Checkbox, Text, ActivityIndicator, Snackbar } from 'react-native-paper';
import { clearDatabase } from '../api/admin';
// Remove useNavigation import if no longer needed elsewhere in this file
// import { useNavigation } from '@react-navigation/native';
import { useAuth } from '../contexts/AuthContext'; // Import useAuth

const AdminScreen = () => {
  const [isHardClear, setIsHardClear] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [snackbarVisible, setSnackbarVisible] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState('');
  // const navigation = useNavigation(); // Remove if not used elsewhere
  const { logout } = useAuth(); // Get the logout function from context

  const handleClearDb = async () => {
    setIsLoading(true);
    setSnackbarVisible(false);
    try {
      const response = await clearDatabase(isHardClear);
      setSnackbarMessage(response.message || 'Database cleared successfully.');
      setSnackbarVisible(true);

      // If hard clear was successful, trigger the logout process from AuthContext
      if (isHardClear) {
        console.log('Hard clear successful, calling logout...');
        await logout(); // Call the logout function from AuthContext
        // The RootNavigator will automatically switch to the AuthFlow
        // No need to manually navigate or set loading to false here
        return; // Exit early
      }

    } catch (error: any) {
      console.error("Error clearing database:", error);
      setSnackbarMessage(error.response?.data?.detail || 'Failed to clear database.');
      setSnackbarVisible(true);
    } finally {
      // Only set loading to false if it wasn't a hard clear (as logout handles navigation)
      if (!isHardClear) {
          setIsLoading(false);
      }
    }
  };

  return (
    <View style={styles.container}>
      <Text variant="headlineMedium" style={styles.title}>Admin Controls</Text>

      <View style={styles.checkboxContainer}>
        <Checkbox
          status={isHardClear ? 'checked' : 'unchecked'}
          onPress={() => setIsHardClear(!isHardClear)}
        />
        <Text onPress={() => setIsHardClear(!isHardClear)}>Hard Clear (Delete all data)</Text>
      </View>

      <Button
        mode="contained"
        onPress={handleClearDb}
        disabled={isLoading}
        style={styles.button}
        buttonColor="red" // Make it look dangerous
      >
        {isLoading ? <ActivityIndicator animating={true} color="white" /> : 'Clear Database'}
      </Button>

      <Snackbar
        visible={snackbarVisible}
        onDismiss={() => setSnackbarVisible(false)}
        duration={Snackbar.DURATION_SHORT}
      >
        {snackbarMessage}
      </Snackbar>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    marginBottom: 30,
  },
  checkboxContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 20,
  },
  button: {
    marginTop: 10,
  },
});

export default AdminScreen;