import { Box, Card, CardContent, Typography } from '@mui/material'
import Grid from '@mui/material/Grid'
import { Link } from 'react-router-dom'
import { useEffect, useState } from 'react'
import api from '../lib/api'

interface HomeworkType {
    id: number
    title: string
    description: string
    reset_type: string
    clear_count: number
}

export default function HomeworkList() {
    const [homeworks, setHomeworks] = useState<HomeworkType[]>([])

    useEffect(() => {
        const fetchHomeworks = async () => {
            try {
                const res = await api.get('/homeworks')
                setHomeworks(res.data)
            } catch (err) {
                console.error('숙제 목록을 불러오는 데 실패했습니다.', err)
            }
        }
        fetchHomeworks()
    }, [])

    return (
        <Box sx={{ p: 4 }}>
            <Typography variant="h5" gutterBottom>
                숙제 목록
            </Typography>

            <Grid container spacing={2}>
                {homeworks.map((hw) => (
                    <Grid item key={hw.id} xs={12} sm={6} md={4} {...({} as any)}>
                        <Card>
                            <CardContent>
                                <Typography variant="h6">{hw.title}</Typography>
                                <Typography>주기: {hw.reset_type}</Typography>
                                <Typography>횟수: {hw.clear_count}</Typography>
                            </CardContent>
                        </Card>
                    </Grid>
                ))}
                <Grid item xs={12} sm={6} md={4} {...({} as any)}>
                    <Card
                        component={Link}
                        to="/homeworks/register"
                        sx={{
                            height: '100%',
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'center',
                            textDecoration: 'none',
                        }}
                    >
                        <CardContent>
                            <Typography variant="h6" align="center">
                                + 숙제 추가
                            </Typography>
                        </CardContent>
                    </Card>
                </Grid>
            </Grid>
        </Box>
    )
}
