import React, { useState } from 'react';
import { Card, CardContent, Typography, TextField, Button, Alert, Stack } from '@mui/material';
import { useAdminSession } from '../../contexts/AdminSessionContext.jsx';

const AdminLoginForm = () => {
  const { login, refreshStatus } = useAdminSession();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState(null);

  const handleSubmit = async (event) => {
    event.preventDefault();
    setSubmitting(true);
    setError(null);

    try {
      await login({ username, password });
      await refreshStatus();
    } catch (loginError) {
      if (loginError.code === 'INVALID_CREDENTIALS') {
        setError('Benutzername oder Passwort ist ungültig.');
      } else if (loginError.code === 'SETUP_REQUIRED') {
        setError('Initiales Setup erforderlich. Bitte Setup-Assistent ausführen.');
      } else {
        setError(loginError.message || 'Login fehlgeschlagen.');
      }
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Card className="admin-auth-card">
      <CardContent>
        <Typography variant="h5" component="h1" gutterBottom>
          Admin Login
        </Typography>
        <Typography variant="body2" color="text.secondary" gutterBottom>
          Bitte melden Sie sich an, um das Moderations-Dashboard zu öffnen.
        </Typography>
        {error && (
          <Alert severity="error" sx={{ mb: 2 }}>
            {error}
          </Alert>
        )}
        <form onSubmit={handleSubmit} className="admin-auth-form">
          <Stack spacing={2}>
            <TextField
              label="Benutzername"
              fullWidth
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              autoComplete="username"
              required
            />
            <TextField
              label="Passwort"
              type="password"
              fullWidth
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              autoComplete="current-password"
              required
            />
            <Button
              variant="contained"
              color="primary"
              type="submit"
              disabled={submitting}
            >
              {submitting ? 'Anmeldung…' : 'Anmelden'}
            </Button>
          </Stack>
        </form>
      </CardContent>
    </Card>
  );
};

export default AdminLoginForm;
