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

interface Character {
    id: number
    name: string
    server: string
}

interface Homework {
    id: number
    title: string
    reset_type: string
    clear_count: number
    complete_cnt: number
}

export default function FriendCharacterDashboard() {
    const { friend_id } = useParams()
    const [characters, setCharacters] = useState<Character[]>([])
    const [homeworks, setHomeworks] = useState<Record<number, Homework[]>>({})
    const navigate = useNavigate()

    useEffect(() => {
        const fetchData = async () => {
            try {
                const res = await api.get(`/friends/${friend_id}/characters`)
                setCharacters(res.data)

                const hwResults = await Promise.all(
                    res.data.map((char: Character) =>
                        api
                            .get(`/friends/${friend_id}/characters/${char.id}/homeworks`)
                            .then(r => ({ id: char.id, data: r.data }))
                    )
                )
                const map: Record<number, Homework[]> = {}
                hwResults.forEach(item => {
                    map[item.id] = item.data
                })
                setHomeworks(map)
            } catch (err) {
                console.error('친구 대시보드 데이터를 불러오는 데 실패했습니다.', err)
            }
        }
        fetchData()
    }, [friend_id])

    return (
        <Box sx={{ p: 4 }}>
            <Button variant="outlined" onClick={() => navigate(-1)} sx={{ mb: 2 }}>
                뒤로가기
            </Button>
            <Typography variant="h5" gutterBottom>
                친구 캐릭터 보기
            </Typography>
            <Grid container spacing={2}>
                {characters.map(char => (
                    <Grid item xs={12} sm={6} md={4} key={char.id} {...({} as any)}>
                        <Card>
                            <CardContent>
                                <Typography variant="h6" gutterBottom>
                                    {char.server} : {char.name}
                                </Typography>
                                <Stack spacing={1}>
                                    {(homeworks[char.id] || []).map(hw => (
                                        <Box key={hw.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
                                                        size="small"
                                                    />
                                                ))}
                                            </Stack>
                                        </Box>
                                    ))}
                                </Stack>
                            </CardContent>
                        </Card>
                    </Grid>
                ))}
            </Grid>
        </Box>
    )
}
