import { useState, useEffect } from 'react';
import { Box, Button, TextField, MenuItem } from '@mui/material';
import { createExternalData, updateExternalData } from '../../api/mongo/actions';

export default function AddOrEditAdminForm({ onAdd, initialData, onCancel }) {
    const [formData, setFormData] = useState({
        name: '',
        description: '',
        status: 'Active'
    });

    useEffect(() => {
        if (initialData) {
            setFormData({ ...initialData });
        } else {
            setFormData({
                name: '',
                description: '',
                status: 'Active'
            });
        }
    }, [initialData]);

    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData(prev => ({ ...prev, [name]: value }));
    };

    const handleSubmit = async () => {
        try {
            if (initialData) {
                await updateExternalData(formData);
            } else {
                await createExternalData(formData);
            }
            if (onAdd) onAdd();
        } catch (error) {
            console.error('Error submitting form:', error);
        }
    };

    return (

        <Box sx={{ py: 2 }}>
            <TextField
                fullWidth
                label="Name"
                name="name"
                value={formData.name}
                onChange={handleChange}
                margin="normal"
            />
            <TextField
                fullWidth
                label="Description"
                name="description"
                value={formData.description}
                onChange={handleChange}
                margin="normal"
            />
            <TextField
                fullWidth
                select
                label="Status"
                name="status"
                value={formData.status}
                onChange={handleChange}
                margin="normal"
            >
                <MenuItem value="Active">Active</MenuItem>
                <MenuItem value="Inactive">Inactive</MenuItem>
            </TextField>
            <Box display="flex" justifyContent="flex-end" mt={3} gap={1}>
                <Button onClick={onCancel} className="button-transparent">Cancel</Button>
                <Button variant="contained" onClick={handleSubmit} className="button-gold">Save</Button>
            </Box>

        </Box>
    );
}