'use client';

import { useEffect, useState } from 'react';
import { useAuth, UserRole } from '@/contexts/AuthContext';
import { db } from '@/lib/firebase';
import { collection, query, orderBy, onSnapshot, doc, updateDoc, QuerySnapshot, DocumentData, QueryDocumentSnapshot } from 'firebase/firestore';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';
import { confirmDialog } from '@/lib/confirm';

interface UserData {
    id: string;
    email: string;
    displayName: string;
    customName?: string;
    photoURL: string;
    role: UserRole;
    createdAt: any;
    lastLoginAt: any;
    lastActiveAt: any;
}

export default function AdminUsersPage() {
    const { user, userRole, loading } = useAuth();
    const router = useRouter();
    const [users, setUsers] = useState<UserData[]>([]);

    // Admin Check
    useEffect(() => {
        if (!loading && (!user || userRole !== 'admin')) {
            router.push('/');
        }
    }, [user, userRole, loading, router]);

    // Fetch Users
    useEffect(() => {
        if (userRole !== 'admin') return;

        const q = query(collection(db, 'users'), orderBy('createdAt', 'desc'));
        const unsubscribe = onSnapshot(q, (snapshot: QuerySnapshot<DocumentData>) => {
            const usersData = snapshot.docs.map((doc: QueryDocumentSnapshot<DocumentData>) => ({
                id: doc.id,
                ...doc.data()
            } as UserData));
            setUsers(usersData);
        });

        return () => unsubscribe();
    }, [userRole]);

    const handleRoleUpdate = async (userId: string, newRole: UserRole) => {
        if (!(await confirmDialog(`${newRole} 권한으로 변경하시겠습니까?`))) return;
        try {
            await updateDoc(doc(db, 'users', userId), { role: newRole });
        } catch (error) {
            console.error('Error updating role:', error);
            toast.error('권한 변경 중 오류가 발생했습니다.');
        }
    };

    const handleCustomNameUpdate = async (userId: string, newCustomName: string) => {
        try {
            // Trim and save as null if empty, otherwise save the string
            const trimmedName = newCustomName.trim();
            await updateDoc(doc(db, 'users', userId), { customName: trimmedName || null });
        } catch (error) {
            console.error('Error updating custom name:', error);
            toast.error('이름 변경 중 오류가 발생했습니다.');
        }
    };

    if (loading || (userRole !== 'admin')) {
        return (
            <div className="min-h-screen flex items-center justify-center">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"></div>
            </div>
        );
    }

    return (
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
            <div className="sm:flex sm:items-center">
                <div className="sm:flex-auto">
                    <h1 className="text-2xl font-semibold text-gray-900">사용자 관리</h1>
                    <p className="mt-2 text-sm text-gray-700">
                        전체 사용자 목록을 조회하고 권한을 관리합니다.
                    </p>
                </div>
            </div>

            <div className="mt-8 flex flex-col">
                <div className="-my-2 -mx-4 overflow-x-auto sm:-mx-6 lg:-mx-8">
                    <div className="inline-block min-w-full py-2 align-middle md:px-6 lg:px-8">
                        <div className="overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg">
                            <table className="min-w-full divide-y divide-gray-300">
                                <thead className="bg-gray-50">
                                    <tr>
                                        <th scope="col" className="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6">사용자</th>
                                        <th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">이메일</th>
                                        <th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">표시 이름</th>
                                        <th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">현재 권한</th>
                                        <th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">상태 관리</th>
                                        <th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">가입일</th>
                                        <th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">최근 사용일자</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-200 bg-white">
                                    {users.map((userData) => (
                                        <tr key={userData.id}>
                                            <td className="whitespace-nowrap py-4 pl-4 pr-3 text-sm sm:pl-6">
                                                <div className="flex items-center">
                                                    <div className="h-10 w-10 flex-shrink-0">
                                                        {userData.photoURL ? (
                                                            <img className="h-10 w-10 rounded-full" src={userData.photoURL} alt="" />
                                                        ) : (
                                                            <div className="h-10 w-10 rounded-full bg-gray-200 flex items-center justify-center">
                                                                <span className="text-gray-500 text-xs">No Img</span>
                                                            </div>
                                                        )}
                                                    </div>
                                                    <div className="ml-4">
                                                        <div className="font-medium text-gray-900">{userData.displayName || '이름 없음'}</div>
                                                        <div className="text-gray-500 text-xs">UID: {userData.id.slice(0, 8)}...</div>
                                                    </div>
                                                </div>
                                            </td>
                                            <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
                                                {userData.email}
                                            </td>
                                            <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
                                                <input
                                                    type="text"
                                                    className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6 px-2"
                                                    placeholder={userData.displayName}
                                                    defaultValue={userData.customName || ''}
                                                    onBlur={(e) => handleCustomNameUpdate(userData.id, e.target.value)}
                                                    onKeyDown={(e) => {
                                                        if (e.key === 'Enter') {
                                                            e.currentTarget.blur();
                                                        }
                                                    }}
                                                />
                                            </td>
                                            <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
                                                <span className={`inline-flex rounded-full px-2 text-xs font-semibold leading-5 ${userData.role === 'admin' ? 'bg-purple-100 text-purple-800' :
                                                    userData.role === 'reviewer' ? 'bg-green-100 text-green-800' :
                                                        userData.role === 'member' ? 'bg-blue-100 text-blue-800' :
                                                            'bg-gray-100 text-gray-800'
                                                    }`}>
                                                    {userData.role}
                                                </span>
                                            </td>
                                            <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
                                                <select
                                                    value={userData.role}
                                                    onChange={(e) => handleRoleUpdate(userData.id, e.target.value as UserRole)}
                                                    className="block w-full rounded-md border-0 py-1.5 pl-3 pr-10 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-indigo-600 sm:text-sm sm:leading-6"
                                                    disabled={userData.id === user?.uid} // 자기 자신 권한 변경 방지
                                                >
                                                    <option value="guest">Guest</option>
                                                    <option value="member">Member</option>
                                                    <option value="reviewer">Reviewer</option>
                                                    <option value="admin">Admin</option>
                                                </select>
                                            </td>
                                            <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
                                                {userData.createdAt?.toDate().toLocaleDateString()}
                                            </td>
                                            <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
                                                {(userData.lastActiveAt ?? userData.lastLoginAt)?.toDate().toLocaleDateString() || '-'}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}
