import React, { useState } from 'react';
import {
    Button, TextField, Dialog, DialogTitle, DialogContent, DialogActions,
    CircularProgress, Alert
} from '@mui/material';

const NewMeetingDialog = ({ open, onClose, onCreate }) => {
    const [topic, setTopic] = useState('');
    const [meetingDate, setMeetingDate] = useState(new Date().toISOString().split('T')[0]); // Defaults to today
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');

    const handleCreate = async () => {
        if (!topic || !meetingDate) {
            setError('Both topic and date are required.');
            return;
        }
        setError('');
        setLoading(true);
        try {
            // The onCreate prop is expected to be an async function
            // that returns the newly created meeting.
            await onCreate(topic, meetingDate);
            handleClose(); // Close the dialog on success
        } catch (err) {
            setError(err.message || 'Failed to create meeting.');
        } finally {
            setLoading(false);
        }
    };

    const handleClose = () => {
        if (loading) return; // Prevent closing while loading
        setTopic('');
        setMeetingDate(new Date().toISOString().split('T')[0]);
        setError('');
        onClose(); // Call the parent's onClose handler
    };

    return (
        <Dialog open={open} onClose={handleClose} fullWidth maxWidth="xs">
            <DialogTitle>Create a New Meeting</DialogTitle>
            <DialogContent>
                {error && <Alert severity="error" sx={{ mb: 2, mt: 1 }}>{error}</Alert>}
                <TextField
                    autoFocus
                    margin="dense"
                    id="topic"
                    label="Meeting Topic"
                    type="text"
                    fullWidth
                    variant="standard"
                    value={topic}
                    onChange={(e) => setTopic(e.target.value)}
                    sx={{ mt: 2 }}
                />
                <TextField
                    margin="dense"
                    id="meetingDate"
                    label="Meeting Date"
                    type="date"
                    fullWidth
                    variant="standard"
                    value={meetingDate}
                    onChange={(e) => setMeetingDate(e.target.value)}
                    InputLabelProps={{
                        shrink: true,
                    }}
                    sx={{ mt: 2 }}
                />
            </DialogContent>
            <DialogActions>
                <Button onClick={handleClose} disabled={loading}>Cancel</Button>
                <Button onClick={handleCreate} variant="contained" disabled={loading}>
                    {loading ? <CircularProgress size={24} /> : 'Create'}
                </Button>
            </DialogActions>
        </Dialog>
    );
};

export default NewMeetingDialog;
