import {
    Box,
    TextField,
    Button,
    Typography,
    MenuItem,
    Container
} from '@mui/material'
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import api from '../lib/api'

export default function RegisterHomework() {
    const [title, setTitle] = useState('')
    const [description, setDescription] = useState('')
    const [resetType, setResetType] = useState('')
    const [clearCount, setClearCount] = useState(0)
    const [error, setError] = useState('')
    const navigate = useNavigate()

    const handleSubmit = async () => {
        setError('')
        try {
            await api.post('/homeworks', {
                title,
                description,
                reset_type: resetType,
                clear_count: clearCount,
            })
            navigate('/homeworks')
        } catch (err) {
            setError('숙제 등록에 실패했습니다.')
            console.error(err)
        }
    }

    return (
        <Container maxWidth="sm">
            <Typography variant="h5" sx={{ mt: 4, mb: 2 }}>
                숙제 등록
            </Typography>
            <TextField
                fullWidth
                label="숙제명"
                margin="normal"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
            />
            <TextField
                fullWidth
                label="설명"
                margin="normal"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
            />
            <TextField
                select
                fullWidth
                label="주기"
                margin="normal"
                value={resetType}
                onChange={(e) => setResetType(e.target.value)}
            >
                <MenuItem value="daily">매일</MenuItem>
                <MenuItem value="weekly">매주</MenuItem>
                <MenuItem value="monthly">매달</MenuItem>
            </TextField>
            <TextField
                fullWidth
                type="number"
                label="횟수"
                margin="normal"
                inputProps={{ min: 0, max: 10 }}
                value={clearCount}
                onChange={(e) => setClearCount(parseInt(e.target.value) || 0)}
            />
            {error && <Typography color="error">{error}</Typography>}
            <Button fullWidth variant="contained" sx={{ mt: 2 }} onClick={handleSubmit}>
                등록하기
            </Button>
        </Container>
    )
}
