import {
    Box, Button, Container, Paper, TextField, Typography, MenuItem,
    Dialog, DialogTitle, DialogContent, DialogContentText, DialogActions,
    FormControlLabel, Checkbox
} from '@mui/material'
import { useEffect, useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import api from '../lib/api'

export default function HomeworkEditPage() {
    const { id } = useParams()
    const navigate = useNavigate()

    const [title, setTitle] = useState('')
    const [description, setDescription] = useState('')
    const [resetType, setResetType] = useState('')
    const [clearCount, setClearCount] = useState('')
    const [isPublic, setIsPublic] = useState(false)
    const [error, setError] = useState('')
    const [openConfirm, setOpenConfirm] = useState(false)

    useEffect(() => {
        api.get(`/homeworks/${id}`)
            .then(res => {
                const hw = res.data
                setTitle(hw.title)
                setDescription(hw.description || '')
                setResetType(hw.reset_type)
                setClearCount(String(hw.clear_count || ''))
                setIsPublic(Boolean(hw.is_public))
            })
            .catch(() => setError('숙제 정보를 불러오는 데 실패했습니다.'))
    }, [id])

    const handleUpdate = async () => {
        try {
            await api.put(`/homeworks/${id}`, {
                title,
                description,
                reset_type: resetType,
                clear_count: Number(clearCount),
                is_public: isPublic,
            })
            navigate('/homeworks')
        } catch {
            setError('숙제 수정에 실패했습니다.')
        }
    }

    const handleDelete = async () => {
        try {
            await api.delete(`/homeworks/${id}`)
            navigate('/homeworks')
        } catch {
            setError('숙제 삭제에 실패했습니다.')
        }
    }

    return (
        <Container maxWidth="sm" sx={{ mt: 4 }}>
            <Typography variant="h5" gutterBottom>숙제 수정</Typography>

            <Paper sx={{ p: 3 }}>
                <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                    <TextField
                        label="숙제 이름"
                        value={title}
                        onChange={(e) => setTitle(e.target.value)}
                        fullWidth
                    />
                    <TextField
                        label="설명"
                        value={description}
                        onChange={(e) => setDescription(e.target.value)}
                        fullWidth
                    />
                    <TextField
                        select
                        label="초기화 주기"
                        value={resetType}
                        onChange={(e) => setResetType(e.target.value)}
                        fullWidth
                    >
                        <MenuItem value="daily">매일</MenuItem>
                        <MenuItem value="weekly">매주</MenuItem>
                        <MenuItem value="monthly">매월</MenuItem>
                        <MenuItem value="none">없음</MenuItem>
                    </TextField>
                    <TextField
                        label="최대 클리어 횟수"
                        value={clearCount}
                        onChange={(e) => setClearCount(e.target.value)}
                        type="number"
                        fullWidth
                    />
                    <FormControlLabel
                        control={<Checkbox checked={isPublic} onChange={e => setIsPublic(e.target.checked)} />}
                        label="친구에게 노출"
                    />

                    {error && <Typography color="error">{error}</Typography>}

                    <Box display="flex" justifyContent="space-between" gap={2}>
                        <Button variant="contained" onClick={handleUpdate}>수정</Button>
                        <Button variant="outlined" color="error" onClick={() => setOpenConfirm(true)}>삭제</Button>
                    </Box>
                </Box>
            </Paper>

            <Dialog open={openConfirm} onClose={() => setOpenConfirm(false)}>
                <DialogTitle>숙제 삭제 확인</DialogTitle>
                <DialogContent>
                    <DialogContentText>정말 이 숙제를 삭제하시겠습니까?</DialogContentText>
                </DialogContent>
                <DialogActions>
                    <Button onClick={() => setOpenConfirm(false)}>취소</Button>
                    <Button onClick={handleDelete} color="error">삭제</Button>
                </DialogActions>
            </Dialog>
        </Container>
    )
}
