import { Grid, InputAdornment } from "@mui/material";
import ButtonJbs from "./button";
import InputJbs from "./input";
import { Add } from "@mui/icons-material";
import { useState, useCallback } from "react";

export default function AddSection({ onCreate, ...props }) {
    const [isEditing, setIsEditing] = useState(false);
    const [title, setTitle] = useState("");

    const handleSubmit = useCallback(() => {
        const trimmedTitle = title.trim();
        if (trimmedTitle) {
            onCreate({ title: trimmedTitle });
            setIsEditing(false);
            setTitle("");
        }
    }, [title, onCreate]);

    const handleKeyPress = useCallback((e) => {
        if (e.key === 'Enter') {
            handleSubmit();
        } else if (e.key === 'Escape') {
            setIsEditing(false);
            setTitle("");
        }
    }, [handleSubmit]);

    const startEditing = useCallback(() => setIsEditing(true), []);

    if (isEditing) {
        return (
            <Grid container>
                <Grid size={12}>
                    <InputJbs
                        value={title}
                        onChange={(e) => setTitle(e.target.value)}
                        onKeyDown={handleKeyPress}
                        size="small"
                        label="Section Name"
                        autoFocus
                        placeholder="Enter section name"
                        InputProps={{
                            endAdornment: (
                                <InputAdornment position="end">
                                    <ButtonJbs 
                                        color="success" 
                                        variant="text" 
                                        onClick={handleSubmit}
                                        disabled={!title.trim()}
                                    >
                                        Save
                                    </ButtonJbs>
                                </InputAdornment>
                            ),
                        }}
                    />
                </Grid>
            </Grid>
        );
    }

    return (
        <Grid container>
            <Grid size={12}>
                <ButtonJbs 
                    className="w-full" 
                    startIcon={<Add />} 
                    onClick={startEditing}
                >
                    Add Section
                </ButtonJbs>
            </Grid>
        </Grid>
    );
}