'use client'

import Link from 'next/link'
import { useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import Image from 'next/image'

type BlockedUser = {
    id: string
    displayName: string
    avatar: string | null
    blockedAt: string
}

interface BlockedUsersTableProps {
    sortBy?: 'latest' | 'nickname'
    searchNickname?: string
    onUnblock?: () => void
}

export default function BlockedUsersTable({ sortBy = 'latest', searchNickname = '', onUnblock }: BlockedUsersTableProps) {
    // Translations
    const { t } = useTranslation()

    // States
    const [blockedUsers, setBlockedUsers] = useState<BlockedUser[]>([])
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        const fetchBlockedUsers = async () => {
            try {
                setLoading(true)
                const response = await fetch('/api/profile/blocked-users')
                const data = await response.json()
                if (data.ok && data.data) {
                    setBlockedUsers(data.data)
                }
            } catch (error) {
                console.error('Failed to fetch blocked users:', error)
            } finally {
                setLoading(false)
            }
        }

        fetchBlockedUsers()
    }, [])

    const handleUnblock = async (userId: string) => {
        try {
            const response = await fetch(`/api/users/${encodeURIComponent(userId)}/block`, {
                method: 'POST',
            })
            const data = await response.json()
            if (data.ok) {
                setBlockedUsers((prev) => prev.filter((user) => user.id !== userId))
                if (onUnblock) {
                    onUnblock()
                }
            }
        } catch (error) {
            console.error('Failed to unblock user:', error)
        }
    }

    let filteredUsers = [...blockedUsers]

    if (searchNickname) {
        filteredUsers = filteredUsers.filter((user) =>
            user.displayName.toLowerCase().includes(searchNickname.toLowerCase())
        )
    }

    if (sortBy === 'nickname') {
        filteredUsers.sort((a, b) => a.displayName.localeCompare(b.displayName))
    }

    if (loading) {
        return (
            <div className="overflow-x-auto min-h-[260px]">
                <div className="py-24 text-center text-sm text-gray-600 dark:text-gray-400">
                    {t('common.loading')}
                </div>
            </div>
        )
    }

    return (
        <div className="overflow-x-auto min-h-[260px]">
            <table className="w-full border-collapse">
                <colgroup>
                    <col style={{ width: '40%' }} />
                    <col style={{ width: '30%' }} />
                    <col style={{ width: '30%' }} />
                </colgroup>
                <thead>
                    <tr className="bg-gray-50 dark:bg-gray-900">
                        <th className="h-11 border-b border-gray-200 dark:border-gray-700 text-center text-sm font-medium text-gray-700 dark:text-gray-200">
                            {t('common.nicknameAndId')}
                        </th>
                        <th className="h-11 border-b border-gray-200 dark:border-gray-700 text-center text-sm font-medium text-gray-700 dark:text-gray-200">
                            {t('common.blockedAt')}
                        </th>
                        <th className="h-11 border-b border-gray-200 dark:border-gray-700 text-center text-sm font-medium text-gray-700 dark:text-gray-200">
                            {t('common.unblock')}
                        </th>
                    </tr>
                </thead>
                <tbody>
                    {filteredUsers.length === 0 ? (
                        <tr>
                            <td
                                className="py-24 border-b border-gray-100 dark:border-gray-800 text-center text-sm text-gray-600 dark:text-gray-400"
                                colSpan={3}
                            >
                                {t('profile.hidden.empty')}
                            </td>
                        </tr>
                    ) : (
                        filteredUsers.map((user) => (
                            <tr key={user.id} className="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-900/50">
                                <td className="py-3 px-4 text-center">
                                    <div className="flex items-center justify-center gap-2">
                                        <Link
                                            href={`/user/${encodeURIComponent(user.id)}`}
                                            className="flex items-center gap-2 max-w-full group"
                                        >
                                            <div className="relative w-8 h-8 rounded-full overflow-hidden flex-shrink-0">
                                                <Image
                                                    src={user.avatar || '/images/user/default_avatar.webp'}
                                                    alt={user.displayName}
                                                    fill
                                                    className="object-cover pointer-events-none"
                                                />
                                            </div>
                                            <div className="text-sm text-gray-900 dark:text-gray-100 truncate group-hover:underline">
                                                {user.displayName}
                                            </div>
                                        </Link>
                                    </div>
                                </td>
                                <td className="py-3 px-4 text-center text-sm text-gray-600 dark:text-gray-400">
                                    {user.blockedAt}
                                </td>
                                <td className="py-3 px-4 text-center">
                                    <button
                                        type="button"
                                        onClick={() => handleUnblock(user.id)}
                                        className="inline-flex items-center justify-center h-8 px-4 rounded-lg text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
                                    >
                                        {t('common.unblock')}
                                    </button>
                                </td>
                            </tr>
                        ))
                    )}
                </tbody>
            </table>
        </div>
    )
}


