// frontend/src/pages/LoginPage.tsx
import React, { useState } from 'react';
import { Container, Typography, Box, Alert } from '@mui/material';
import PassphraseInput from '../components/PassphraseInput';
import { authenticate, setSessionToken } from '../services/authService';
import { useNavigate, useLocation } from 'react-router-dom';

const LoginPage: React.FC = () => {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const navigate = useNavigate();
  const location = useLocation();
  const from = location.state?.from?.pathname || '/';

  const handleSubmitPassphrase = async (passphrase: string) => {
    setIsLoading(true);
    setError(null);
    try {
      const sessionToken = await authenticate(passphrase);
      setSessionToken(sessionToken);
      navigate(from, { replace: true }); // Redirect to the original intended page
    } catch (err: any) {
      setError(err.message || 'An unknown error occurred.');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Container component="main" maxWidth="xs">
      <Box
        sx={{
          marginTop: 8,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'flex-start',
        }}
      >
        <Typography component="h1" variant="h5" sx={{ textAlign: 'left', width: '100%' }}>
          Enter Passphrase
        </Typography>
        {error && (
          <Alert severity="error" sx={{ width: '100%', mt: 2 }}>
            {error}
          </Alert>
        )}
        <PassphraseInput onSubmit={handleSubmitPassphrase} isLoading={isLoading} error={null} />
      </Box>
    </Container>
  );
};

export default LoginPage;
