// src/components/admin/AddClientForm.tsx
'use client';
import { useState } from 'react';
import { Button, TextField, DialogContent, DialogActions, Alert } from '@mui/material';
import api from '@/lib/axios';

interface Props {
  onClose: () => void;
  onClientCreated?: () => void;
}

export default function AddClientForm({ onClose, onClientCreated }: Props) {
  const [clientName, setClientName] = useState('');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  const handleSubmit = async () => {
    try {
      const res = await api.post('/auth/register/client', { clientName });
      setSuccess(`Client ID: ${res.data.clientId}, Identifier: ${res.data.clientIdentifier}`);
      setClientName('');
      setError('');
      if (onClientCreated) onClientCreated();
      onClose();
    } catch (err: any) {
      setError(err.response?.data?.message || 'Unexpected error');
      setSuccess('');
    }
  };

  return (
    <>
      <DialogContent>
        <TextField
          fullWidth
          margin="dense"
          label="Client Name"
          value={clientName}
          onChange={(e) => setClientName(e.target.value)}
        />
        {error && <Alert severity="error" sx={{ mt: 2 }}>{error}</Alert>}
        {success && <Alert severity="success" sx={{ mt: 2 }}>{success}</Alert>}
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Cancel</Button>
        <Button variant="contained" onClick={handleSubmit}>Register</Button>
      </DialogActions>
    </>
  );
}
