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

interface Character {
    id: number
    name: string
    server: string
    job?: string
    combat_power?: number
}

interface Homework {
    homework_id: number
    title: string
    assigned: 'Y' | 'N'
    reset_type: string
    clear_count: number
    loading?: boolean // 체크박스 클릭 처리 중 여부
}

export default function CharacterHomeworkSelect() {
    const [characters, setCharacters] = useState<Character[]>([])
    const [homeworkMap, setHomeworkMap] = useState<Record<number, Homework[]>>({})
    const [loadingMap, setLoadingMap] = useState<Record<number, boolean>>({})

    // 캐릭터 목록 불러오기
    useEffect(() => {
        const fetchCharacters = async () => {
            try {
                const res = await api.get('/characters')
                setCharacters(res.data)
            } catch (err) {
                console.error('캐릭터 목록을 불러오는 데 실패했습니다.', err)
            }
        }
        fetchCharacters()
    }, [])

    // 캐릭터별 숙제 불러오기
    useEffect(() => {
        characters.forEach(async (char) => {
            setLoadingMap(prev => ({ ...prev, [char.id]: true }))
            try {
                const res = await api.get(`/characterHomework/${char.id}/homeworks/selectable`)
                setHomeworkMap(prev => ({ ...prev, [char.id]: res.data }))
            } catch (err) {
                console.error(`캐릭터 ${char.name}의 숙제를 불러오는 데 실패했습니다.`, err)
            } finally {
                setLoadingMap(prev => ({ ...prev, [char.id]: false }))
            }
        })
    }, [characters])

    // 숙제 지정/해제
    const toggleHomework = async (characterId: number, hw: Homework) => {
        const homework_type_id = hw.homework_id

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

        try {
            if (hw.assigned === 'Y') {
                // 지정 해제
                await api.delete(`/characters/${characterId}/homeworks/${homework_type_id}`)
                updateHomeworkState(characterId, homework_type_id, 'N')
            } else {
                // 숙제 지정
                await api.post(`/characters/${characterId}/homeworks/${homework_type_id}`)
                updateHomeworkState(characterId, homework_type_id, 'Y')
            }
        } catch (err) {
            console.error('숙제 상태 변경 실패:', err)
            alert('숙제 지정/해제에 실패했습니다.')
        } finally {
            // 로딩 종료
            setHomeworkMap(prev => ({
                ...prev,
                [characterId]: prev[characterId].map(h =>
                    h.homework_id === hw.homework_id ? { ...h, loading: false } : h
                )
            }))
        }
    }

    // 상태만 갱신
    const updateHomeworkState = (
        characterId: number,
        homeworkId: number,
        assigned: 'Y' | 'N'
    ) => {
        setHomeworkMap(prev => ({
            ...prev,
            [characterId]: prev[characterId].map(h =>
                h.homework_id === homeworkId ? { ...h, assigned } : h
            )
        }))
    }

    return (
        <Box sx={{ p: 4 }}>
            <Typography variant="h5" gutterBottom>
                내 숙제 관리
            </Typography>
            <Grid container spacing={2}>
                {characters.map((char) => (
                    <Grid component="div" item key={char.id} xs={12} sm={6} md={4} {...({} as any)}>
                        <Card sx={{ p: 2 }}>
                            <CardContent>
                                <Typography variant="h6">{char.name}</Typography>
                                {loadingMap[char.id] ? (
                                    <CircularProgress size={20} sx={{ mt: 2 }} />
                                ) : (
                                    <Stack spacing={1} mt={2}>
                                        {(homeworkMap[char.id] || []).map(hw => (
                                            <FormControlLabel
                                                key={hw.homework_id}
                                                control={
                                                    hw.loading ? (
                                                        <CircularProgress size={18} />
                                                    ) : (
                                                        <Checkbox
                                                            checked={hw.assigned === 'Y'}
                                                            onChange={() => toggleHomework(char.id, hw)}
                                                        />
                                                    )
                                                }
                                                label={`${hw.title} (${hw.reset_type} ${hw.clear_count}회)`}
                                            />
                                        ))}
                                    </Stack>
                                )}
                            </CardContent>
                        </Card>
                    </Grid>
                ))}
            </Grid>
        </Box>
    )
}
