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

interface Friend {
    id: number
    email: string
}

export default function FriendListPage() {
    const [friends, setFriends] = useState<Friend[]>([])
    const [showDialog, setShowDialog] = useState(false)
    const navigate = useNavigate()

    useEffect(() => {
        const fetchFriends = async () => {
            try {
                const res = await api.get('/friends/list')
                setFriends(res.data)
            } catch (e) {
                console.error('친구 목록 불러오기 실패', e)
            }
        }
        fetchFriends()
    }, [])

    return (
        <Container sx={{ mt: 4 }}>
            <Typography variant="h5" gutterBottom>
                친구 목록
            </Typography>
            <Grid container spacing={2}>
                {friends.map(friend => (
                    <Grid item xs={12} sm={6} md={4} key={friend.id} {...({} as any)}>
                        <Card>
                            <CardContent>
                                <Typography variant="h6">{friend.email}</Typography>
                                <Box sx={{ mt: 1 }}>
                                    <Button
                                        variant="outlined"
                                        onClick={() =>
                                            navigate(`/friends/${friend.id}/characters`)
                                        }
                                    >
                                        캐릭터 보기
                                    </Button>
                                </Box>
                            </CardContent>
                        </Card>
                    </Grid>
                ))}
                <Grid item xs={12} sm={6} md={4} {...({} as any)}>
                    <Card
                        onClick={() => setShowDialog(true)}
                        sx={{
                            height: '100%',
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'center',
                            cursor: 'pointer',
                        }}
                    >
                        <CardContent>
                            <Typography variant="h6" align="center">
                                + 친구 추가
                            </Typography>
                        </CardContent>
                    </Card>
                </Grid>
            </Grid>

            {showDialog && <FriendSearchDialog onClose={() => setShowDialog(false)} />}
        </Container>
    )
}
