import { useState } from 'react';
import { 
  Box, 
  Typography, 
  Button, 
  TextField, 
  Card, 
  CardContent, 
  Stack,
  Alert,
  CircularProgress
} from '@mui/material';
import { useNavigate } from 'react-router-dom';
import { useSessionStore } from '../store/sessionStore';

const HomePage = () => {
  const navigate = useNavigate();
  const { isSessionUnlocked, unlockSession, createKeyspace } = useSessionStore();
  
  const [keyspace, setKeyspace] = useState<string>('');
  const [password, setPassword] = useState<string>('');
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const [mode, setMode] = useState<'unlock' | 'create'>('unlock');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setIsLoading(true);
    
    try {
      let success = false;
      
      if (mode === 'unlock') {
        success = await unlockSession(keyspace, password);
      } else {
        success = await createKeyspace(keyspace, password);
      }
      
      if (success) {
        // Navigate to keypair page on success
        navigate('/keypair');
      } else {
        setError(mode === 'unlock' 
          ? 'Failed to unlock keyspace. Check your password and try again.' 
          : 'Failed to create keyspace. Please try again.');
      }
    } catch (err) {
      setError((err as Error).message || 'An unexpected error occurred');
    } finally {
      setIsLoading(false);
    }
  };

  if (isSessionUnlocked) {
    return (
      <Box sx={{ textAlign: 'center', py: 4 }}>
        <Typography variant="h5" gutterBottom>
          Welcome to Hero Vault
        </Typography>
        <Typography variant="body1" color="text.secondary" paragraph>
          Your session is unlocked. You can now use the extension features.
        </Typography>
        <Stack direction="row" spacing={2} justifyContent="center" mt={3}>
          <Button 
            variant="contained" 
            color="primary"
            onClick={() => navigate('/keypair')}
          >
            Manage Keys
          </Button>
          <Button 
            variant="outlined" 
            color="secondary"
            onClick={() => navigate('/script')}
          >
            Run Scripts
          </Button>
        </Stack>
      </Box>
    );
  }

  return (
    <Box sx={{ maxWidth: 400, mx: 'auto', py: 2 }}>
      <Typography variant="h5" align="center" gutterBottom>
        Hero Vault
      </Typography>
      
      <Card variant="outlined" sx={{ mt: 3 }}>
        <CardContent>
          <Typography variant="h6" gutterBottom>
            {mode === 'unlock' ? 'Unlock Keyspace' : 'Create New Keyspace'}
          </Typography>
          
          {error && (
            <Alert severity="error" sx={{ mb: 2 }}>
              {error}
            </Alert>
          )}
          
          <form onSubmit={handleSubmit}>
            <TextField
              label="Keyspace Name"
              value={keyspace}
              onChange={(e) => setKeyspace(e.target.value)}
              fullWidth
              margin="normal"
              required
              disabled={isLoading}
            />
            
            <TextField
              label="Password"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              fullWidth
              margin="normal"
              required
              disabled={isLoading}
            />
            
            <Box sx={{ mt: 3, display: 'flex', justifyContent: 'space-between' }}>
              <Button
                variant="text"
                onClick={() => setMode(mode === 'unlock' ? 'create' : 'unlock')}
                disabled={isLoading}
              >
                {mode === 'unlock' ? 'Create New Keyspace' : 'Unlock Existing'}
              </Button>
              
              <Button
                type="submit"
                variant="contained"
                color="primary"
                disabled={isLoading || !keyspace || !password}
              >
                {isLoading ? (
                  <CircularProgress size={24} color="inherit" />
                ) : mode === 'unlock' ? (
                  'Unlock'
                ) : (
                  'Create'
                )}
              </Button>
            </Box>
          </form>
        </CardContent>
      </Card>
    </Box>
  );
};

export default HomePage;
