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

const ForcePasswordChangeForm = () => {
  const { user, refreshStatus } = useAdminSession();
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(null);

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

    if (!currentPassword) {
      setError('Bitte aktuelles Passwort eingeben.');
      return;
    }

    if (newPassword.length < 10) {
      setError('Das neue Passwort muss mindestens 10 Zeichen lang sein.');
      return;
    }

    if (newPassword !== confirmPassword) {
      setError('Die neuen Passwörter stimmen nicht überein.');
      return;
    }

    setSubmitting(true);
    try {
      await changePassword({ currentPassword, newPassword });
      setSuccess('Passwort wurde aktualisiert. Bitte erneut anmelden falls nötig.');
      setCurrentPassword('');
      setNewPassword('');
      setConfirmPassword('');
      await refreshStatus();
    } catch (changeError) {
      if (changeError.code === 'INVALID_CURRENT_PASSWORD') {
        setError('Das aktuelle Passwort ist falsch.');
      } else if (changeError.code === 'PASSWORD_TOO_WEAK') {
        setError('Das neue Passwort ist zu schwach (mindestens 10 Zeichen).');
      } else {
        setError(changeError.message || 'Passwort konnte nicht geändert werden.');
      }
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Card className="admin-auth-card">
      <CardContent>
        <Typography variant="h5" component="h1" gutterBottom>
          Passwort aktualisieren
        </Typography>
        <Typography variant="body2" color="text.secondary" gutterBottom>
          Der Benutzer "{user?.username}" muss das initiale Passwort ändern, bevor das Dashboard genutzt werden kann.
        </Typography>
        {error && (
          <Alert severity="error" sx={{ mb: 2 }}>
            {error}
          </Alert>
        )}
        {success && (
          <Alert severity="success" sx={{ mb: 2 }}>
            {success}
          </Alert>
        )}
        <form onSubmit={handleSubmit} className="admin-auth-form">
          <Stack spacing={2}>
            <TextField
              label="Aktuelles Passwort"
              type="password"
              fullWidth
              value={currentPassword}
              onChange={(e) => setCurrentPassword(e.target.value)}
              autoComplete="current-password"
              required
            />
            <TextField
              label="Neues Passwort"
              type="password"
              fullWidth
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              autoComplete="new-password"
              required
            />
            <TextField
              label="Neues Passwort bestätigen"
              type="password"
              fullWidth
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              autoComplete="new-password"
              required
            />
            <Button
              variant="contained"
              color="primary"
              type="submit"
              disabled={submitting}
            >
              {submitting ? 'Aktualisiere...' : 'Passwort speichern'}
            </Button>
          </Stack>
        </form>
      </CardContent>
    </Card>
  );
};

export default ForcePasswordChangeForm;
