"use client";

import { useState } from 'react';
import { formatDistanceToNow } from 'date-fns';
import { UserFilterState } from './UserManagementDashboard';
import { AlertCircle, CheckCircle2, ChevronLeft, ChevronRight, Mail, MoreVertical, Search, ShieldAlert, ShieldCheck, Trash2, X, XCircle } from 'lucide-react';
import Link from 'next/link';
import { User } from '@prisma/client';
import Image from 'next/image';

type AdminListUser = User & {
    _count?: { jobs?: number; applications?: number };
    avatar_url?: string | null;
    avatarUrl?: string | null;
};

interface UserListTableProps {
    users: AdminListUser[];
    loading: boolean;
    filters: UserFilterState;
    setFilters: React.Dispatch<React.SetStateAction<UserFilterState>>;
    pagination: { total: number; page: number; limit: number; totalPages: number };
    onRefresh?: () => void;
}

export function UserListTable({ users, loading, filters, setFilters, pagination, onRefresh }: UserListTableProps) {
    const [selectedIds, setSelectedIds] = useState<string[]>([]);
    const [actionLoading, setActionLoading] = useState(false);
    const [feedback, setFeedback] = useState<{ type: 'success' | 'error' | 'warning', message: string, details?: { id: string; reason: string }[] } | null>(null);

    const toggleSelectAll = () => {
        if (selectedIds.length === users.length) {
            setSelectedIds([]);
        } else {
            setSelectedIds(users.map(u => u.id));
        }
    };

    const toggleSelect = (id: string) => {
        setSelectedIds(prev =>
            prev.includes(id) ? prev.filter(userId => userId !== id) : [...prev, id]
        );
    };

    const handleBulkAction = async (action: 'suspend' | 'unsuspend' | 'verify' | 'delete') => {
        if (!confirm(`Are you sure you want to perform this action (${action}) on ${selectedIds.length} user(s)?`)) return;

        setActionLoading(true);
        setFeedback(null);

        try {
            const res = await fetch('/api/admin/users/bulk-actions', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ userIds: selectedIds, action })
            });

            const data = await res.json();

            if (!res.ok) {
                throw new Error(data.error || 'Failed to process bulk action');
            }

            // Error Aggregation Handling Pattern
            if (data.results?.failed?.length > 0) {
                setFeedback({
                    type: data.results.success.length > 0 ? 'warning' : 'error',
                    message: data.message,
                    details: data.results.failed
                });
            } else {
                setFeedback({ type: 'success', message: data.message });
                setSelectedIds([]); // clear selection fully on success
            }

            if (onRefresh && data.results?.success?.length > 0) {
                onRefresh();
            }

        } catch (error: unknown) {
            console.error(error);
            setFeedback({ type: 'error', message: (error as Error).message });
        } finally {
            setActionLoading(false);
        }
    };

    if (loading) {
        return (
            <div className="p-12 text-center relative pointer-events-none">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto opacity-50"></div>
            </div>
        );
    }

    if (users.length === 0) {
        return (
            <div className="p-12 text-center">
                <div className="bg-slate-50 w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4">
                    <Search className="w-8 h-8 text-slate-400" />
                </div>
                <h3 className="text-lg font-medium text-slate-900">No users found</h3>
                <p className="text-slate-500 mt-1">Try adjusting your filters or search query.</p>
                <button
                    onClick={() => setFilters({ search: '', roles: [], status: 'all', page: 1, limit: 50 })}
                    className="mt-4 text-blue-600 text-sm hover:underline"
                >
                    Clear all filters
                </button>
            </div>
        );
    }

    return (
        <div className="overflow-x-auto relative min-h-[400px]">
            {/* Feedback Toast */}
            {feedback && (
                <div className={`m-4 p-4 rounded-lg flex items-start gap-3 border ${feedback.type === 'success' ? 'bg-green-50 border-green-200 text-green-800' :
                    feedback.type === 'warning' ? 'bg-amber-50 border-amber-200 text-amber-800' :
                        'bg-red-50 border-red-200 text-red-800'
                    }`}>
                    {feedback.type === 'success' ? <CheckCircle2 className="w-5 h-5 shrink-0" /> : <AlertCircle className="w-5 h-5 shrink-0" />}
                    <div className="flex-1">
                        <p className="font-medium text-sm">{feedback.message}</p>
                        {feedback.details && feedback.details.length > 0 && (
                            <ul className="mt-2 text-xs opacity-80 list-disc list-inside space-y-1">
                                {feedback.details.map((err, i) => (
                                    <li key={i}>ID: {err.id} - {err.reason}</li>
                                ))}
                            </ul>
                        )}
                    </div>
                    <button onClick={() => setFeedback(null)} className="opacity-50 hover:opacity-100">
                        <X className="w-4 h-4" />
                    </button>
                </div>
            )}

            {/* Bulk Actions Header */}
            {selectedIds.length > 0 && (
                <div className="bg-blue-50 border-b border-blue-200 px-6 py-3 flex items-center justify-between sticky top-0 z-10 animate-in fade-in slide-in-from-top-4 duration-200">
                    <div className="flex items-center gap-4">
                        <span className="text-sm font-medium text-blue-800 bg-blue-100 px-2 py-1 rounded">
                            {selectedIds.length} {selectedIds.length === 1 ? 'user' : 'users'} selected
                        </span>
                        <div className="h-4 w-px bg-blue-200"></div>
                        <div className="flex items-center gap-2">
                            <button
                                onClick={() => handleBulkAction('suspend')}
                                disabled={actionLoading}
                                className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-amber-700 bg-amber-100/50 hover:bg-amber-100 rounded-md transition-colors disabled:opacity-50"
                            >
                                <ShieldAlert className="w-4 h-4" /> Suspend
                            </button>
                            <button
                                onClick={() => handleBulkAction('unsuspend')}
                                disabled={actionLoading}
                                className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-green-700 bg-green-100/50 hover:bg-green-100 rounded-md transition-colors disabled:opacity-50"
                            >
                                <CheckCircle2 className="w-4 h-4" /> Unsuspend
                            </button>
                            <button
                                onClick={() => handleBulkAction('verify')}
                                disabled={actionLoading}
                                className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-purple-700 bg-purple-100/50 hover:bg-purple-100 rounded-md transition-colors disabled:opacity-50"
                            >
                                <ShieldCheck className="w-4 h-4" /> Verify
                            </button>
                            <button
                                onClick={() => handleBulkAction('delete')}
                                disabled={actionLoading}
                                className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-red-700 bg-red-100/50 hover:bg-red-100 rounded-md transition-colors ml-4 disabled:opacity-50"
                            >
                                <Trash2 className="w-4 h-4" /> Delete
                            </button>
                        </div>
                    </div>
                    <button
                        onClick={() => setSelectedIds([])}
                        className="text-sm text-blue-600 hover:text-blue-800 font-medium"
                    >
                        Cancel
                    </button>
                </div>
            )}

            <table className="w-full text-left border-collapse">
                <thead>
                    <tr className="bg-slate-50 border-b border-slate-200">
                        <th className="px-6 py-4 flex items-center gap-3 w-16">
                            <input
                                type="checkbox"
                                checked={users.length > 0 && selectedIds.length === users.length}
                                onChange={toggleSelectAll}
                                className="rounded border-slate-300 text-blue-600 focus:ring-blue-500 w-4 h-4 cursor-pointer"
                            />
                            <span className="text-xs font-semibold text-slate-500 uppercase tracking-wider">User</span>
                        </th>
                        <th className="px-6 py-4 text-xs font-semibold text-slate-500 uppercase tracking-wider">Role</th>
                        <th className="px-6 py-4 text-xs font-semibold text-slate-500 uppercase tracking-wider">Status</th>
                        <th className="px-6 py-4 text-xs font-semibold text-slate-500 uppercase tracking-wider">Joined</th>
                        <th className="px-6 py-4 text-xs font-semibold text-slate-500 uppercase tracking-wider">Metrics</th>
                        <th className="px-6 py-4 text-right text-xs font-semibold text-slate-500 uppercase tracking-wider">Actions</th>
                    </tr>
                </thead>
                <tbody className="divide-y divide-slate-200 bg-white">
                    {users.map((user) => (
                        <tr
                            key={user.id}
                            onClick={() => toggleSelect(user.id)}
                            className={`transition-colors group cursor-pointer ${selectedIds.includes(user.id) ? 'bg-blue-50/50' : 'hover:bg-slate-50'}`}
                        >
                            <td className="px-6 py-4">
                                <div className="flex items-center gap-3">
                                    <input
                                        type="checkbox"
                                        checked={selectedIds.includes(user.id)}
                                        onChange={() => toggleSelect(user.id)}
                                        onClick={e => e.stopPropagation()}
                                        className="rounded border-slate-300 text-blue-600 focus:ring-blue-500 w-4 h-4 cursor-pointer opacity-0 group-hover:opacity-100 transition-opacity"
                                        style={{ opacity: selectedIds.includes(user.id) ? 1 : undefined }}
                                    />
                                    <div className="relative h-10 w-10 shrink-0">
                                        <div className="h-10 w-10 rounded-full bg-slate-200 flex items-center justify-center text-slate-500 font-bold overflow-hidden border border-slate-200">
                                            {user.avatarUrl ? (
                                                <Image src={user.avatarUrl} alt={user.name} fill className="object-cover" />
                                            ) : (
                                                user.name.charAt(0).toUpperCase()
                                            )}
                                        </div>
                                    </div>
                                    <div>
                                        <div className="font-medium text-slate-900 group-hover:text-blue-600 transition-colors">
                                            {user.name}
                                        </div>
                                        <div className="text-sm text-slate-500 flex items-center gap-1.5">
                                            <Mail className="w-3 h-3" />
                                            {user.email}
                                        </div>
                                    </div>
                                </div>
                            </td>
                            <td className="px-6 py-4">
                                <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium capitalize
                                    ${user.role === 'candidate' ? 'bg-blue-100 text-blue-800' :
                                        user.role === 'employer' ? 'bg-purple-100 text-purple-800' :
                                            'bg-slate-100 text-slate-800'}`}>
                                    {user.role}
                                </span>
                            </td>
                            <td className="px-6 py-4">
                                {user.is_active ? (
                                    <span className="flex items-center gap-1.5 text-sm text-green-700">
                                        <CheckCircle2 className="w-4 h-4 text-green-500" /> Active
                                    </span>
                                ) : (
                                    <span className="flex items-center gap-1.5 text-sm text-red-700">
                                        <XCircle className="w-4 h-4 text-red-500" /> Suspended
                                    </span>
                                )}
                            </td>
                            <td className="px-6 py-4">
                                <div className="text-sm text-slate-900">
                                    {new Date(user.created_at).toLocaleDateString()}
                                </div>
                                <div className="text-xs text-slate-500">
                                    {formatDistanceToNow(new Date(user.created_at), { addSuffix: true })}
                                </div>
                            </td>
                            <td className="px-6 py-4">
                                <div className="text-sm text-slate-600">
                                    {user.role === 'employer' ? (
                                        <span><strong className="text-slate-900">{user._count?.jobs || 0}</strong> Jobs</span>
                                    ) : user.role === 'candidate' ? (
                                        <span><strong className="text-slate-900">{user._count?.applications || 0}</strong> Apps</span>
                                    ) : (
                                        <span>-</span>
                                    )}
                                </div>
                            </td>
                            <td className="px-6 py-4 text-right">
                                <Link
                                    href={`/admin/users/${user.id}`}
                                    onClick={(e) => e.stopPropagation()}
                                    className="inline-flex items-center justify-center p-2 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors border border-transparent hover:border-blue-100"
                                >
                                    View Details
                                </Link>
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>

            {/* Pagination Controls */}
            <div className="flex items-center justify-between border-t border-slate-200 bg-white px-6 py-3">
                <div className="hidden sm:flex sm:flex-1 sm:items-center sm:justify-between">
                    <div>
                        <p className="text-sm text-slate-700">
                            Showing <span className="font-medium">{((pagination.page - 1) * pagination.limit) + 1}</span> to <span className="font-medium">{Math.min(pagination.page * pagination.limit, pagination.total)}</span> of{' '}
                            <span className="font-medium">{pagination.total}</span> results
                        </p>
                    </div>
                    <div>
                        <nav className="isolate inline-flex -space-x-px rounded-md shadow-sm" aria-label="Pagination">
                            <button
                                onClick={() => setFilters(prev => ({ ...prev, page: Math.max(1, prev.page - 1) }))}
                                disabled={pagination.page === 1 || actionLoading}
                                className="relative inline-flex items-center rounded-l-md px-2 py-2 text-slate-400 ring-1 ring-inset ring-slate-300 hover:bg-slate-50 focus:z-20 focus:outline-offset-0 disabled:opacity-50 disabled:cursor-not-allowed"
                            >
                                <span className="sr-only">Previous</span>
                                <ChevronLeft className="h-5 w-5" aria-hidden="true" />
                            </button>

                            {/* Simple page display */}
                            <span className="relative inline-flex items-center px-4 py-2 text-sm font-semibold text-slate-900 ring-1 ring-inset ring-slate-300 focus:z-20 focus:outline-offset-0">
                                {pagination.page} / {pagination.totalPages || 1}
                            </span>

                            <button
                                onClick={() => setFilters(prev => ({ ...prev, page: Math.min(pagination.totalPages, prev.page + 1) }))}
                                disabled={pagination.page === pagination.totalPages || pagination.totalPages === 0 || actionLoading}
                                className="relative inline-flex items-center rounded-r-md px-2 py-2 text-slate-400 ring-1 ring-inset ring-slate-300 hover:bg-slate-50 focus:z-20 focus:outline-offset-0 disabled:opacity-50 disabled:cursor-not-allowed"
                            >
                                <span className="sr-only">Next</span>
                                <ChevronRight className="h-5 w-5" aria-hidden="true" />
                            </button>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    );
}
