import { useEffect, useState } from 'react'
import api from '../lib/api'

interface FriendRequest {
    id: number
    from_user_id: number
    to_user_id: number
    from_user_email?: string
    to_user_email?: string
    status: 'pending' | 'accepted' | 'rejected' | 'cancelled'
    created_at: string
}

export default function FriendRequestsPage() {
    const [tab, setTab] = useState<'received' | 'sent'>('received')
    const [requests, setRequests] = useState<FriendRequest[]>([])
    const [emailMap, setEmailMap] = useState<Record<number, string>>({})

    useEffect(() => {
        const fetchRequests = async () => {
            const url =
                tab === 'received' ? '/friends/requests/received' : '/friends/requests/sent'
            const res = await api.get(url)
            setRequests(res.data)

            const emails = await Promise.all(
                res.data.map(async (r: FriendRequest) => {
                    const targetId = tab === 'received' ? r.from_user_id : r.to_user_id
                    const emailFromResponse =
                        tab === 'received' ? r.from_user_email : r.to_user_email
                    if (emailFromResponse) {
                        return [targetId, emailFromResponse] as [number, string]
                    }
                    const user = await api.get(`/users/${targetId}`)
                    return [targetId, user.data.email] as [number, string]
                })
            )
            setEmailMap(Object.fromEntries(emails))
        }
        fetchRequests()
    }, [tab])

    const handleRespond = async (id: number, accept: boolean) => {
        await api.post(`/friends/requests/${id}/respond`, null, { params: { accept } })
        alert(accept ? '친구 요청을 수락했습니다.' : '친구 요청을 거절했습니다.')
        const req = requests.find(r => r.id === id)
        const targetId = req ? (tab === 'received' ? req.from_user_id : req.to_user_id) : null
        setRequests(prev => prev.filter(r => r.id !== id))
        if (targetId !== null) {
            setEmailMap(prev => {
                const newMap = { ...prev }
                delete newMap[targetId]
                return newMap
            })
        }
    }

    const handleCancel = async (id: number) => {
        await api.post(`/friends/requests/${id}/cancel`)
        alert('요청을 취소했습니다.')
        const req = requests.find(r => r.id === id)
        const targetId = req ? (tab === 'received' ? req.from_user_id : req.to_user_id) : null
        setRequests(prev => prev.filter(r => r.id !== id))
        if (targetId !== null) {
            setEmailMap(prev => {
                const newMap = { ...prev }
                delete newMap[targetId]
                return newMap
            })
        }
    }

    return (
        <div>
            <h2>친구 요청 관리</h2>
            <div>
                <button onClick={() => setTab('received')}>받은 요청</button>
                <button onClick={() => setTab('sent')}>보낸 요청</button>
            </div>

            {requests.length === 0 ? (
                <p>요청이 없습니다.</p>
            ) : (
                <ul>
                    {requests.map(req => {
                        const targetId = tab === 'received' ? req.from_user_id : req.to_user_id
                        const email = emailMap[targetId] || '로딩중...'
                        return (
                            <li key={req.id}>
                                {email}{' '}
                                {tab === 'received' ? (
                                    <>
                                        <button onClick={() => handleRespond(req.id, true)}>수락</button>
                                        <button onClick={() => handleRespond(req.id, false)}>거부</button>
                                    </>
                                ) : (
                                    <button onClick={() => handleCancel(req.id)}>취소</button>
                                )}
                            </li>
                        )
                    })}
                </ul>
            )}
        </div>
    )
}
