import React, { useState } from 'react';
import { View, StyleSheet } from 'react-native';
import { Button, Checkbox, Text, ActivityIndicator, Snackbar, TextInput, Divider, useTheme } from 'react-native-paper'; // Added TextInput, Divider, useTheme
import { clearDatabase } from '../api/admin';
import apiClient from '../api/client'; // Import apiClient
import { useAuth } from '../contexts/AuthContext';

const AdminScreen = () => {
  const theme = useTheme(); // Get theme for styling if needed

  // --- State for Clear DB ---
  const [isHardClear, setIsHardClear] = useState(false);
  const [isClearingDb, setIsClearingDb] = useState(false); // Renamed from isLoading
  const [clearDbSnackbarVisible, setClearDbSnackbarVisible] = useState(false); // Renamed
  const [clearDbSnackbarMessage, setClearDbSnackbarMessage] = useState(''); // Renamed

  // --- State for Send Notification ---
  const [username, setUsername] = useState('');
  const [title, setTitle] = useState('');
  const [body, setBody] = useState('');
  const [isSendingNotification, setIsSendingNotification] = useState(false); // New loading state
  const [notificationError, setNotificationError] = useState<string | null>(null); // New error state
  const [notificationSuccess, setNotificationSuccess] = useState<string | null>(null); // New success state

  const { logout } = useAuth();

  // --- Clear DB Handler ---
  const handleClearDb = async () => {
    setIsClearingDb(true); // Use renamed state
    setClearDbSnackbarVisible(false);
    try {
      const response = await clearDatabase(isHardClear);
      setClearDbSnackbarMessage(response.message || 'Database cleared successfully.');
      setClearDbSnackbarVisible(true);

      if (isHardClear) {
        console.log('Hard clear successful, calling logout...');
        await logout();
        return;
      }

    } catch (error: any) {
      console.error("Error clearing database:", error);
      setClearDbSnackbarMessage(error.response?.data?.detail || 'Failed to clear database.');
      setClearDbSnackbarVisible(true);
    } finally {
      if (!isHardClear) {
          setIsClearingDb(false); // Use renamed state
      }
    }
  };

  // --- Send Notification Handler ---
  const handleSendNotification = async () => {
    if (!username || !title || !body) {
        setNotificationError('Username, Title, and Body are required.');
        setNotificationSuccess(null);
        return;
    }

    setIsSendingNotification(true);
    setNotificationError(null);
    setNotificationSuccess(null);

    try {
        const response = await apiClient.post('/admin/send-notification', {
            username,
            title,
            body,
            // data: {} // Add optional data payload if needed
        });

        if (response.status === 200) {
            setNotificationSuccess(response.data.message || 'Notification sent successfully!');
            // Clear fields after success
            setUsername('');
            setTitle('');
            setBody('');
        } else {
            setNotificationError(response.data?.detail || 'Failed to send notification.');
        }
    } catch (err: any) {
        console.error("Error sending notification:", err.response?.data || err.message);
        setNotificationError(err.response?.data?.detail || 'An error occurred while sending the notification.');
    } finally {
        setIsSendingNotification(false);
    }
  };


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

      {/* --- Clear Database Section --- */}
      <Text variant="titleMedium" style={styles.sectionTitle}>Clear Database</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={isClearingDb} // Use renamed state
        style={styles.button}
        buttonColor="red"
      >
        {isClearingDb ? <ActivityIndicator animating={true} color="white" /> : 'Clear Database'}
      </Button>
      <Snackbar
        visible={clearDbSnackbarVisible} // Use renamed state
        onDismiss={() => setClearDbSnackbarVisible(false)}
        duration={Snackbar.DURATION_SHORT}
      >
        {clearDbSnackbarMessage} {/* Use renamed state */}
      </Snackbar>

      <Divider style={styles.divider} />

      {/* --- Send Notification Section --- */}
      <Text variant="titleMedium" style={styles.sectionTitle}>Send Push Notification</Text>

      {notificationError && <Text style={[styles.message, { color: theme.colors.error }]}>{notificationError}</Text>}
      {notificationSuccess && <Text style={[styles.message, { color: theme.colors.primary }]}>{notificationSuccess}</Text>}

      <TextInput
          label="Username"
          value={username}
          onChangeText={setUsername}
          mode="outlined"
          style={styles.input}
          autoCapitalize="none"
          disabled={isSendingNotification}
      />
      <TextInput
          label="Notification Title"
          value={title}
          onChangeText={setTitle}
          mode="outlined"
          style={styles.input}
          disabled={isSendingNotification}
      />
      <TextInput
          label="Notification Body"
          value={body}
          onChangeText={setBody}
          mode="outlined"
          style={styles.input}
          multiline
          numberOfLines={3}
          disabled={isSendingNotification}
      />
      <Button
          mode="contained"
          onPress={handleSendNotification}
          loading={isSendingNotification}
          disabled={isSendingNotification}
          style={styles.button}
      >
          {isSendingNotification ? 'Sending...' : 'Send Notification'}
      </Button>

    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    // Removed justifyContent and alignItems to allow scrolling if content overflows
  },
  title: {
    marginBottom: 20, // Reduced margin
    textAlign: 'center',
  },
  sectionTitle: {
    marginBottom: 15,
    marginTop: 10, // Add some space before the title
    textAlign: 'center',
  },
  checkboxContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10, // Reduced margin
    justifyContent: 'center', // Center checkbox
  },
  button: {
    marginTop: 10,
    marginBottom: 10, // Add margin below button
  },
  input: {
      marginBottom: 15,
  },
  message: {
      marginBottom: 15,
      textAlign: 'center',
      fontWeight: 'bold',
  },
  divider: {
    marginVertical: 30, // Add vertical space around the divider
  },
});

export default AdminScreen;