import { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  Typography,
} from '@mui/material';
import { membersService } from '../../services/members';

interface Props {
  open: boolean;
  userId: string;
  onClose: () => void;
}

export const FirstLoginDialog = ({ open, userId, onClose }: Props) => {
  const [standesbuchnummer, setStandesbuchnummer] = useState('');
  const [saving, setSaving] = useState(false);

  const handleSave = async () => {
    setSaving(true);
    try {
      if (standesbuchnummer.trim()) {
        await membersService.updateMember(userId, {
          fdisk_standesbuch_nr: standesbuchnummer.trim(),
        });
      }
    } catch {
      // non-fatal, user can update later in profile
    } finally {
      setSaving(false);
      localStorage.setItem('firstLoginCompleted', 'true');
      onClose();
    }
  };

  const handleSkip = () => {
    localStorage.setItem('firstLoginCompleted', 'true');
    onClose();
  };

  return (
    <Dialog open={open} maxWidth="sm" fullWidth>
      <DialogTitle>Willkommen!</DialogTitle>
      <DialogContent>
        <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
          Du wurdest erfolgreich registriert. Bitte gib deine Standesbuchnummer ein, damit dein
          Profil zugeordnet werden kann. Dies kann auch später in deinen Profileinstellungen
          ergänzt werden.
        </Typography>
        <TextField
          label="Standesbuchnummer"
          value={standesbuchnummer}
          onChange={(e) => setStandesbuchnummer(e.target.value)}
          fullWidth
          size="small"
          placeholder="z.B. 12345"
          inputProps={{ maxLength: 32 }}
        />
      </DialogContent>
      <DialogActions>
        <Button onClick={handleSkip} color="inherit">
          Überspringen
        </Button>
        <Button onClick={handleSave} variant="contained" disabled={saving}>
          {saving ? 'Speichern...' : 'Speichern'}
        </Button>
      </DialogActions>
    </Dialog>
  );
};
