import { useState, useEffect } from 'react';
import { Box, Button, TextField, Typography, Paper } from '@mui/material';

export default function AddOrEditCategoryForm({ onAdd, initialData, onCancel }) {
    const [category, setCategory] = useState({
        name: '',
        description: ''
    });

    useEffect(() => {
        if (initialData) {
            setCategory(initialData);
        } else {
            setCategory({ name: '', description: '' });
        }
    }, [initialData]);

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

    const handleSubmit = () => {
        if (onAdd) {
            onAdd(category);
        }
    };

    return (
        <Box sx={{ px: 2, py: 3 }}>
            <Paper elevation={0} sx={{ p: 3, bgcolor: '#f9f9f9', borderRadius: 2 }}>
                <Typography variant="h6" gutterBottom>
                    Category Details
                </Typography>
                <TextField
                    fullWidth
                    label="Name"
                    name="name"
                    value={category.name}
                    onChange={handleChange}
                    margin="normal"
                />
                <TextField
                    fullWidth
                    label="Description"
                    name="description"
                    value={category.description}
                    onChange={handleChange}
                    margin="normal"
                    multiline
                    rows={4}
                />
                <Box display="flex" justifyContent="flex-end" gap={1} mt={3}>
                    <Button onClick={onCancel} className="button-transparent">
                        Cancel
                    </Button>
                    <Button variant="contained" onClick={handleSubmit} className="button-gold">
                        Save
                    </Button>
                </Box>
            </Paper>
        </Box>
    );
}
