import { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Switch,
  // FormControlLabel removed as it's not used
  Divider,
  Paper,
  List,
  ListItem,
  ListItemText,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Alert,
  Snackbar
} from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import InfoIcon from '@mui/icons-material/Info';

interface Settings {
  darkMode: boolean;
  autoLockTimeout: number; // minutes
  confirmCryptoOperations: boolean;
  showScriptNotifications: boolean;
}

const SettingsPage = () => {
  const [settings, setSettings] = useState<Settings>({
    darkMode: true,
    autoLockTimeout: 15,
    confirmCryptoOperations: true,
    showScriptNotifications: true
  });
  
  const [clearDataDialogOpen, setClearDataDialogOpen] = useState(false);
  const [confirmText, setConfirmText] = useState('');
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState('');

  // Load settings from storage
  useEffect(() => {
    const loadSettings = async () => {
      try {
        const data = await chrome.storage.local.get('settings');
        if (data.settings) {
          setSettings(data.settings);
        }
      } catch (err) {
        console.error('Failed to load settings:', err);
      }
    };

    loadSettings();
  }, []);

  // Save settings when changed
  const handleSettingChange = (key: keyof Settings, value: boolean | number) => {
    const updatedSettings = { ...settings, [key]: value };
    setSettings(updatedSettings);
    
    // Save to storage
    chrome.storage.local.set({ settings: updatedSettings })
      .then(() => {
        setSnackbarMessage('Settings saved');
        setSnackbarOpen(true);
      })
      .catch(err => {
        console.error('Failed to save settings:', err);
        setSnackbarMessage('Failed to save settings');
        setSnackbarOpen(true);
      });
  };

  const handleClearAllData = () => {
    if (confirmText !== 'CLEAR ALL DATA') {
      setSnackbarMessage('Please type the confirmation text exactly');
      setSnackbarOpen(true);
      return;
    }
    
    // Clear all extension data
    chrome.storage.local.clear()
      .then(() => {
        setSnackbarMessage('All data cleared successfully');
        setSnackbarOpen(true);
        setClearDataDialogOpen(false);
        setConfirmText('');
        
        // Reset settings to defaults
        setSettings({
          darkMode: true,
          autoLockTimeout: 15,
          confirmCryptoOperations: true,
          showScriptNotifications: true
        });
      })
      .catch(err => {
        console.error('Failed to clear data:', err);
        setSnackbarMessage('Failed to clear data');
        setSnackbarOpen(true);
      });
  };

  return (
    <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <Typography variant="h6" gutterBottom>
        Settings
      </Typography>
      
      <Paper variant="outlined" sx={{ flexGrow: 1, overflow: 'auto' }}>
        <List disablePadding>
          <ListItem>
            <ListItemText
              primary="Dark Mode"
              secondary="Use dark theme for the extension"
            />
            <Switch
              edge="end"
              checked={settings.darkMode}
              onChange={(e) => handleSettingChange('darkMode', e.target.checked)}
            />
          </ListItem>
          
          <Divider />
          
          <ListItem>
            <ListItemText
              primary="Auto-Lock Timeout"
              secondary={`Automatically lock session after ${settings.autoLockTimeout} minutes of inactivity`}
            />
            <Box sx={{ width: 120 }}>
              <TextField
                type="number"
                size="small"
                value={settings.autoLockTimeout}
                onChange={(e) => {
                  const value = parseInt(e.target.value);
                  if (!isNaN(value) && value >= 1) {
                    handleSettingChange('autoLockTimeout', value);
                  }
                }}
                InputProps={{ inputProps: { min: 1, max: 60 } }}
              />
            </Box>
          </ListItem>
          
          <Divider />
          
          <ListItem>
            <ListItemText
              primary="Confirm Cryptographic Operations"
              secondary="Always ask for confirmation before signing or encrypting"
            />
            <Switch
              edge="end"
              checked={settings.confirmCryptoOperations}
              onChange={(e) => handleSettingChange('confirmCryptoOperations', e.target.checked)}
            />
          </ListItem>
          
          <Divider />
          
          <ListItem>
            <ListItemText
              primary="Script Notifications"
              secondary="Show notifications when new scripts are received"
            />
            <Switch
              edge="end"
              checked={settings.showScriptNotifications}
              onChange={(e) => handleSettingChange('showScriptNotifications', e.target.checked)}
            />
          </ListItem>
        </List>
      </Paper>
      
      <Box sx={{ mt: 3 }}>
        <Alert 
          severity="info" 
          icon={<InfoIcon />}
          sx={{ mb: 2 }}
        >
          <Typography variant="body2">
            The extension stores all cryptographic keys in encrypted form. Your password is never stored and is only kept in memory while the session is unlocked.
          </Typography>
        </Alert>
        
        <Button
          variant="outlined"
          color="error"
          startIcon={<DeleteIcon />}
          onClick={() => setClearDataDialogOpen(true)}
          fullWidth
        >
          Clear All Data
        </Button>
      </Box>
      
      {/* Clear Data Confirmation Dialog */}
      <Dialog open={clearDataDialogOpen} onClose={() => setClearDataDialogOpen(false)}>
        <DialogTitle>Clear All Extension Data</DialogTitle>
        <DialogContent>
          <Typography variant="body1" paragraph>
            This will permanently delete all your keyspaces, keypairs, and settings. This action cannot be undone.
          </Typography>
          <Typography variant="body2" color="error" paragraph>
            Type "CLEAR ALL DATA" to confirm:
          </Typography>
          <TextField
            value={confirmText}
            onChange={(e) => setConfirmText(e.target.value)}
            fullWidth
            variant="outlined"
            placeholder="CLEAR ALL DATA"
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setClearDataDialogOpen(false)}>
            Cancel
          </Button>
          <Button 
            onClick={handleClearAllData} 
            color="error"
            disabled={confirmText !== 'CLEAR ALL DATA'}
          >
            Clear All Data
          </Button>
        </DialogActions>
      </Dialog>
      
      {/* Snackbar for notifications */}
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={3000}
        onClose={() => setSnackbarOpen(false)}
        message={snackbarMessage}
      />
    </Box>
  );
};

export default SettingsPage;
