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

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

  const validate = () => {
    if (password !== passwordConfirm) {
      setError('Passwörter stimmen nicht überein.');
      return false;
    }
    if (password.length < 10) {
      setError('Passwort muss mindestens 10 Zeichen lang sein.');
      return false;
    }
    return true;
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    setError(null);
    if (!validate()) {
      return;
    }

    setSubmitting(true);
    try {
      await createInitialAdmin({ username, password });
      await refreshStatus();
    } catch (setupError) {
      if (setupError.code === 'SETUP_ALREADY_COMPLETED') {
        setError('Setup wurde bereits durchgeführt. Bitte anmelden.');
      } else if (setupError.code === 'USERNAME_IN_USE') {
        setError('Benutzername ist bereits vergeben.');
      } else if (setupError.code === 'PASSWORD_TOO_WEAK') {
        setError('Passwort entspricht nicht den Mindestanforderungen.');
      } else {
        setError(setupError.message || 'Initiales Setup fehlgeschlagen.');
      }
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Card className="admin-auth-card">
      <CardContent>
        <Typography variant="h5" component="h1" gutterBottom>
          Initialer Admin-Zugang
        </Typography>
        <Typography variant="body2" color="text.secondary" gutterBottom>
          Es wurde noch kein Admin-Benutzer angelegt. Bitte erstellen Sie den ersten Account.
        </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)}
              helperText="Mindestens 10 Zeichen"
              autoComplete="new-password"
              required
            />
            <TextField
              label="Passwort bestätigen"
              type="password"
              fullWidth
              value={passwordConfirm}
              onChange={(e) => setPasswordConfirm(e.target.value)}
              autoComplete="new-password"
              required
            />
            <Button
              variant="contained"
              color="primary"
              type="submit"
              disabled={submitting}
            >
              {submitting ? 'Speichern…' : 'Admin anlegen'}
            </Button>
          </Stack>
        </form>
      </CardContent>
    </Card>
  );
};

export default InitialAdminSetupForm;
