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

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

export default function CharacterList() {
    const [characters, setCharacters] = useState<Character[]>([])

    useEffect(() => {
        const fetchCharacters = async () => {
            try {
                const response = await api.get('/characters')
                setCharacters(response.data)
            } catch (err) {
                console.error('캐릭터 목록을 불러오는 중 오류 발생:', err)
            }
        }

        fetchCharacters()
    }, [])

    return (
        <Container sx={{ mt: 4 }}>
            <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">{char.name}</Typography>
                                <Typography color="text.secondary">서버: {char.server || '-'}</Typography>
                                <Typography color="text.secondary">직업: {char.job || '-'}</Typography>
                                <Typography color="text.secondary">전투력: {char.combat_power?.toLocaleString() || '-'}</Typography>
                            </CardContent>
                        </Card>
                    </Grid>
                ))}
                <Grid item xs={12} sm={6} md={4} {...({} as any)}>
                    <Card
                        component={Link}
                        to="/characters/register"
                        sx={{ height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center', textDecoration: 'none' }}
                    >
                        <CardContent>
                            <Typography variant="h6" align="center">
                                + 캐릭터 추가
                            </Typography>
                        </CardContent>
                    </Card>
                </Grid>
            </Grid>
        </Container>
    )
}
