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 [friendIds, setFriendIds] = useState<number[]>([])
    const [friends, setFriends] = useState<Friend[]>([])
    const [showDialog, setShowDialog] = useState(false)
    const navigate = useNavigate()

    useEffect(() => {
        const fetchFriends = async () => {
            try {
                const ids: number[] = await api.get('/friends/list').then(res => res.data)
                setFriendIds(ids)

                const friendInfos = await Promise.all(
                    ids.map(id => api.get(`/users/${id}`).then(res => res.data))
                )
                setFriends(friendInfos)
            } catch (e) {
                console.error('친구 목록 불러오기 실패', e)
            }
        }
        fetchFriends()
    }, [])

    return (
        <div>
            <h2>친구 목록</h2>
            <button onClick={() => setShowDialog(true)}>+ 친구 추가</button>

            {friends.length === 0 ? (
                <p>친구가 없습니다.</p>
            ) : (
                <ul>
                    {friends.map(friend => (
                        <li key={friend.id}>
                            {friend.email}
                            <button onClick={() => navigate(`/friends/${friend.id}/characters`)}>
                                캐릭터 보기
                            </button>
                        </li>
                    ))}
                </ul>
            )}

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