import {
    Box,
    Typography,
    Card,
    CardContent,
    Grid,
    Stack,
    Checkbox
} from '@mui/material'
import { useEffect, useState } from 'react'
import api from '../lib/api'

interface Character {
    character_id: number
    character_name: string
    server: string
}

interface Homework {
    homework_id: number
    title: string
    reset_type: string
    clear_count: number
    complete_cnt: number
    loading?: boolean
}

export default function Dashboard() {
    const [characters, setCharacters] = useState<Character[]>([])
    const [homeworks, setHomeworks] = useState<Record<number, Homework[]>>({})

    useEffect(() => {
        const fetchDashboard = async () => {
            try {
                const res = await api.get('/dashboard/characters')
                setCharacters(res.data)

                const homeworkResults = await Promise.all(
                    res.data.map((char: Character) =>
                        api
                            .get(`/dashboard/characters/${char.character_id}/homeworks`)
                            .then(r => ({ id: char.character_id, data: r.data }))
                    )
                )

                const map: Record<number, Homework[]> = {}
                homeworkResults.forEach(item => {
                    map[item.id] = item.data
                })

                setHomeworks(map)
            } catch (err) {
                console.error('대시보드 데이터를 불러오는 데 실패했습니다.', err)
            }
        }

        fetchDashboard()
    }, [])

    const handleCheck = async (characterId: number, hw: Homework, index: number) => {
        const newCount = index < hw.complete_cnt ? hw.complete_cnt - 1 : index + 1

        // 로딩 표시
        setHomeworks(prev => ({
            ...prev,
            [characterId]: prev[characterId].map(h =>
                h.homework_id === hw.homework_id ? { ...h, loading: true } : h
            )
        }))

        try {
            await api.patch(`/characterHomework/${characterId}/homeworks/${hw.homework_id}`, {
                complete_cnt: newCount,
            })

            setHomeworks(prev => ({
                ...prev,
                [characterId]: prev[characterId].map(h =>
                    h.homework_id === hw.homework_id
                        ? { ...h, complete_cnt: newCount, loading: false }
                        : h
                )
            }))
        } catch (err) {
            console.error('숙제 체크 반영 실패:', err)
            alert('숙제 체크 반영에 실패했습니다.')

            setHomeworks(prev => ({
                ...prev,
                [characterId]: prev[characterId].map(h =>
                    h.homework_id === hw.homework_id
                        ? { ...h, loading: false }
                        : h
                )
            }))
        }
    }

    return (
        <Box sx={{ p: 4 }}>
            <Typography variant="h5" gutterBottom>숙제 대시보드</Typography>
            <Grid container spacing={2}>
                {characters.map(char => (
                    <Grid item xs={12} sm={6} md={4} key={char.character_id} {...({} as any)}>
                        <Card>
                            <CardContent>
                                <Typography variant="h6" gutterBottom>
                                    {char.server} : {char.character_name}
                                </Typography>
                                <Stack spacing={1}>
                                    {(homeworks[char.character_id] || []).map(hw => (
                                        <Box key={hw.homework_id}>
                                            <Typography variant="subtitle2" gutterBottom>
                                                {hw.title} ({hw.clear_count}회)
                                            </Typography>
                                            <Stack direction="row" spacing={1}>
                                                {Array.from({ length: hw.clear_count }).map((_, idx) => (
                                                    <Checkbox
                                                        key={idx}
                                                        checked={idx < hw.complete_cnt}
                                                        disabled={hw.loading}
                                                        onChange={() =>
                                                            handleCheck(char.character_id, hw, idx)
                                                        }
                                                        size="small"
                                                    />
                                                ))}
                                            </Stack>
                                        </Box>
                                    ))}
                                </Stack>
                            </CardContent>
                        </Card>
                    </Grid>
                ))}
            </Grid>
        </Box>
    )
}
