import AdminLayout from '@/Layouts/AdminLayout';
import { Head, Link, router, usePage } from '@inertiajs/react';
import { Search, ChevronLeft, ChevronRight, UserMinus, Shield, ShieldAlert, BookOpen, ClipboardList } from 'lucide-react';
import { useState, useEffect } from 'react';
import { toast } from 'sonner';

interface User {
    id: number;
    name: string;
    email: string;
    is_admin: boolean;
    created_at: string;
    orders_count: number;
    enrollments_count: number;
}

interface PaginationLink {
    url: string | null;
    label: string;
    active: boolean;
}

interface Props {
    users: {
        data: User[];
        total: number;
        links: PaginationLink[];
        current_page: number;
        last_page: number;
        prev_page_url: string | null;
        next_page_url: string | null;
    };
    filters: {
        search?: string;
        role?: string;
    };
}

export default function Index({ users, filters }: Props) {
    const { auth } = usePage<any>().props;
    const [search, setSearch] = useState(filters.search || '');
    const [role, setRole] = useState(filters.role || 'all');
    const [deleteModalOpen, setDeleteModalOpen] = useState(false);
    const [selectedUser, setSelectedUser] = useState<User | null>(null);

    // Trigger Inertia reload for search / role filters
    const handleFilterChange = (newSearch: string, newRole: string) => {
        router.get(
            route('admin.users.index'),
            { search: newSearch, role: newRole !== 'all' ? newRole : undefined },
            { preserveState: true, replace: true }
        );
    };

    // Debounce search input
    useEffect(() => {
        const timer = setTimeout(() => {
            if (search !== (filters.search || '')) {
                handleFilterChange(search, role);
            }
        }, 400);

        return () => clearTimeout(timer);
    }, [search]);

    const handleRoleSelect = (selectedRole: string) => {
        setRole(selectedRole);
        handleFilterChange(search, selectedRole);
    };

    const handleToggleAdmin = (user: User) => {
        if (user.id === auth.user.id) {
            toast.error('You cannot change your own privileges.');
            return;
        }

        router.patch(route('admin.users.update', user.id), {
            is_admin: !user.is_admin,
        }, {
            onSuccess: () => toast.success('User privileges updated successfully'),
            onError: (err: any) => toast.error(err.error || 'Failed to update user privileges'),
        });
    };

    const confirmDelete = (user: User) => {
        if (user.id === auth.user.id) {
            toast.error('You cannot delete your own account.');
            return;
        }
        setSelectedUser(user);
        setDeleteModalOpen(true);
    };

    const handleDelete = () => {
        if (!selectedUser) return;

        router.delete(route('admin.users.destroy', selectedUser.id), {
            onSuccess: () => {
                toast.success('User deleted successfully');
                setDeleteModalOpen(false);
                setSelectedUser(null);
            },
            onError: () => {
                toast.error('Failed to delete user');
            }
        });
    };

    const userList = users.data || [];

    return (
        <AdminLayout>
            <Head title="User Management" />

            {/* Header */}
            <div className="mb-8">
                <h1 className="font-display text-[1.625rem] font-normal tracking-[-0.02em] text-ink leading-none">
                    Users
                </h1>
                <p className="mt-2.5 text-[0.9375rem] text-[#8C92AC]">
                    Manage user accounts, roles, orders, and course enrollments. Total users: {users.total}
                </p>
            </div>

            {/* Toolbar */}
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
                {/* Role Tabs */}
                <div className="flex items-center gap-0.5 bg-[#F0EDE8] p-1 rounded-lg overflow-x-auto no-scrollbar">
                    {[
                        { id: 'all', label: 'All Users' },
                        { id: 'admin', label: 'Administrators' },
                        { id: 'customer', label: 'Customers' }
                    ].map((tab) => (
                        <button
                            key={tab.id}
                            onClick={() => handleRoleSelect(tab.id)}
                            className={`px-3.5 py-1.5 text-[11px] font-semibold rounded-md transition-all whitespace-nowrap ${
                                role === tab.id
                                    ? 'bg-white shadow-sm text-ink'
                                    : 'text-[#8C92AC] hover:text-ink'
                            }`}
                        >
                            {tab.label}
                        </button>
                    ))}
                </div>

                {/* Search */}
                <div className="relative w-full md:w-64">
                    <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[#8C92AC]" />
                    <input
                        type="text"
                        value={search}
                        onChange={(e) => setSearch(e.target.value)}
                        placeholder="Search name, email…"
                        className="pl-9 pr-4 py-2 bg-white border border-[#E8E6DF] rounded-lg text-[13px] text-ink placeholder:text-[#8C92AC] focus:outline-none focus:ring-2 focus:ring-primary/15 w-full"
                    />
                </div>
            </div>

            {/* Mobile View: Cards */}
            <div className="grid gap-2 md:hidden mb-8">
                {userList.map((user) => {
                    const initials = user.name.split(' ').map((n: string) => n[0]).join('').toUpperCase().slice(0, 2);
                    const isSelf = user.id === auth.user.id;

                    return (
                        <div key={user.id} className="bg-white rounded-[1.25rem] border border-[#E8E6DF] p-5 shadow-sm">
                            <div className="flex items-center justify-between mb-3">
                                <div className="flex items-center gap-2">
                                    <div className="h-8 w-8 rounded-full bg-[#F0EDE8] flex items-center justify-center text-[10px] font-bold text-ink border border-[#E8E6DF]">
                                        {initials}
                                    </div>
                                    <div>
                                        <p className="text-[14px] font-bold text-ink leading-tight flex items-center gap-1.5">
                                            {user.name}
                                            {isSelf && <span className="text-[9px] bg-slate-100 text-slate-600 px-1.5 py-0.5 rounded font-bold uppercase tracking-wider">You</span>}
                                        </p>
                                        <p className="text-[11px] text-[#8C92AC] font-medium mt-0.5">{user.email}</p>
                                    </div>
                                </div>
                                <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wider ${
                                    user.is_admin ? 'bg-indigo-50 text-indigo-700' : 'bg-slate-100 text-[#8C92AC]'
                                }`}>
                                    {user.is_admin ? 'Admin' : 'Customer'}
                                </span>
                            </div>

                            <div className="grid grid-cols-2 gap-4 mt-4 pt-4 border-t border-[#F0EDE8] text-[11px] text-[#8C92AC]">
                                <div className="flex items-center gap-1.5">
                                    <ClipboardList className="h-3.5 w-3.5" />
                                    <span>{user.orders_count} Orders</span>
                                </div>
                                <div className="flex items-center gap-1.5">
                                    <BookOpen className="h-3.5 w-3.5" />
                                    <span>{user.enrollments_count} Courses</span>
                                </div>
                            </div>

                            <div className="flex justify-end gap-2 mt-4 pt-4 border-t border-[#F0EDE8]">
                                <button
                                    onClick={() => handleToggleAdmin(user)}
                                    disabled={isSelf}
                                    className={`px-3 py-1.5 rounded-lg text-[11px] font-semibold transition-all border flex items-center gap-1.5 ${
                                        isSelf 
                                            ? 'opacity-30 cursor-not-allowed border-[#E8E6DF]' 
                                            : 'border-[#E8E6DF] hover:bg-[#FAFAF8] text-ink'
                                    }`}
                                >
                                    <Shield className="h-3.5 w-3.5" />
                                    {user.is_admin ? 'Revoke Admin' : 'Make Admin'}
                                </button>
                                <button
                                    onClick={() => confirmDelete(user)}
                                    disabled={isSelf}
                                    className={`px-3 py-1.5 rounded-lg text-[11px] font-semibold transition-all border flex items-center gap-1.5 ${
                                        isSelf 
                                            ? 'opacity-30 cursor-not-allowed border-[#E8E6DF]' 
                                            : 'border-red-100 bg-red-50 hover:bg-red-100 text-red-600'
                                    }`}
                                >
                                    <UserMinus className="h-3.5 w-3.5" />
                                    Delete
                                </button>
                            </div>
                        </div>
                    );
                })}
                {userList.length === 0 && (
                    <div className="bg-white rounded-[1.25rem] border border-[#E8E6DF] p-12 text-center text-[13px] text-[#8C92AC]">
                        No users found.
                    </div>
                )}
            </div>

            {/* Desktop View: Table */}
            <div className="hidden md:block bg-white rounded-xl border border-[#E8E6DF] overflow-hidden">
                <table className="w-full text-left border-collapse">
                    <thead>
                        <tr className="border-b border-[#F0EDE8]">
                            {['User', 'Role', 'Registered', 'Activity', 'Actions'].map((h) => (
                                <th
                                    key={h}
                                    className="px-6 py-3.5 text-[10px] font-semibold tracking-[0.14em] uppercase text-[#8C92AC]"
                                >
                                    {h}
                                </th>
                            ))}
                        </tr>
                    </thead>
                    <tbody>
                        {userList.map((user) => {
                            const initials = user.name.split(' ').map((n: string) => n[0]).join('').toUpperCase().slice(0, 2);
                            const isSelf = user.id === auth.user.id;
                            const regDate = new Date(user.created_at).toLocaleDateString('en-US', {
                                year: 'numeric',
                                month: 'short',
                                day: 'numeric',
                            });

                            return (
                                <tr
                                    key={user.id}
                                    className="border-b border-[#F0EDE8] last:border-0 hover:bg-[#FAFAF8] transition-colors"
                                >
                                    <td className="px-6 py-4">
                                        <div className="flex items-center gap-3">
                                            <div className="h-9 w-9 rounded-full bg-[#F0EDE8] flex items-center justify-center text-[11px] font-bold text-ink border border-[#E8E6DF] flex-shrink-0">
                                                {initials}
                                            </div>
                                            <div>
                                                <p className="text-[13px] font-semibold text-ink flex items-center gap-1.5">
                                                    {user.name}
                                                    {isSelf && <span className="text-[9px] bg-slate-100 text-slate-600 px-1.5 py-0.5 rounded font-bold uppercase tracking-wider">You</span>}
                                                </p>
                                                <p className="text-[11px] text-[#8C92AC] mt-0.5">{user.email}</p>
                                            </div>
                                        </div>
                                    </td>
                                    <td className="px-6 py-4">
                                        <span className={`inline-flex items-center px-2.5 py-1 rounded-full text-[10px] font-semibold uppercase tracking-wider ${
                                            user.is_admin ? 'bg-indigo-50 text-indigo-700' : 'bg-slate-100 text-[#8C92AC]'
                                        }`}>
                                            {user.is_admin ? 'Admin' : 'Customer'}
                                        </span>
                                    </td>
                                    <td className="px-6 py-4 text-[12px] text-ink">{regDate}</td>
                                    <td className="px-6 py-4">
                                        <div className="flex flex-col gap-1 text-[11px] text-ink">
                                            <span className="flex items-center gap-1"><ClipboardList className="h-3.5 w-3.5 text-[#8C92AC]" /> {user.orders_count} orders</span>
                                            <span className="flex items-center gap-1"><BookOpen className="h-3.5 w-3.5 text-[#8C92AC]" /> {user.enrollments_count} courses</span>
                                        </div>
                                    </td>
                                    <td className="px-6 py-4">
                                        <div className="flex items-center gap-2">
                                            <button
                                                onClick={() => handleToggleAdmin(user)}
                                                disabled={isSelf}
                                                className={`p-2 rounded-lg border transition-all ${
                                                    isSelf
                                                        ? 'opacity-30 cursor-not-allowed border-[#E8E6DF]'
                                                        : 'border-[#E8E6DF] bg-white hover:bg-[#FAFAF8] text-ink'
                                                }`}
                                                title={user.is_admin ? 'Demote to customer' : 'Make admin'}
                                            >
                                                <Shield className="h-4 w-4" />
                                            </button>
                                            <button
                                                onClick={() => confirmDelete(user)}
                                                disabled={isSelf}
                                                className={`p-2 rounded-lg border transition-all ${
                                                    isSelf
                                                        ? 'opacity-30 cursor-not-allowed border-[#E8E6DF]'
                                                        : 'border-red-100 bg-red-50 hover:bg-red-100 text-red-600'
                                                }`}
                                                title="Delete user"
                                            >
                                                <UserMinus className="h-4 w-4" />
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            );
                        })}
                    </tbody>
                </table>
                {userList.length === 0 && (
                    <div className="px-6 py-16 text-center text-[13px] text-[#8C92AC]">
                        No users found.
                    </div>
                )}
            </div>

            {/* Pagination */}
            {users.last_page > 1 && (
                <div className="mt-8 flex flex-col sm:flex-row items-center justify-between gap-4">
                    <p className="text-[11px] text-[#8C92AC] font-medium">
                        Showing page {users.current_page} of {users.last_page}
                    </p>
                    <div className="flex items-center gap-1.5">
                        {users.links.map((link, i) => {
                            const isPrev = i === 0;
                            const isNext = i === users.links.length - 1;
                            
                            if (isPrev) {
                                return (
                                    <Link
                                        key={i}
                                        href={link.url || '#'}
                                        className={`p-2 rounded-lg border border-[#E8E6DF] transition-all ${!link.url ? 'opacity-30 cursor-not-allowed' : 'bg-white hover:bg-[#FAFAF8] text-ink'}`}
                                    >
                                        <ChevronLeft className="h-4 w-4" />
                                    </Link>
                                );
                            }
                            
                            if (isNext) {
                                return (
                                    <Link
                                        key={i}
                                        href={link.url || '#'}
                                        className={`p-2 rounded-lg border border-[#E8E6DF] transition-all ${!link.url ? 'opacity-30 cursor-not-allowed' : 'bg-white hover:bg-[#FAFAF8] text-ink'}`}
                                    >
                                        <ChevronRight className="h-4 w-4" />
                                    </Link>
                                );
                            }

                            const isCurrent = link.active;
                            const pageNum = parseInt(link.label);
                            const isNear = Math.abs(pageNum - users.current_page) <= 1;
                            const isEdge = pageNum === 1 || pageNum === users.last_page;

                            if (isCurrent || isNear || isEdge) {
                                return (
                                    <Link
                                        key={i}
                                        href={link.url || '#'}
                                        className={`min-w-[36px] h-[36px] flex items-center justify-center rounded-lg border text-[12px] font-semibold transition-all ${
                                            link.active
                                                ? 'bg-primary border-primary text-white'
                                                : 'bg-white border-[#E8E6DF] text-ink hover:bg-[#FAFAF8]'
                                        }`}
                                        dangerouslySetInnerHTML={{ __html: link.label }}
                                    />
                                );
                            }
                            
                            if (pageNum === users.current_page - 2 || pageNum === users.current_page + 2) {
                                return <span key={i} className="px-1 text-[#8C92AC]">...</span>;
                            }

                            return null;
                        })}
                    </div>
                </div>
            )}

            {/* Delete Modal */}
            {deleteModalOpen && selectedUser && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-ink/40 backdrop-blur-sm">
                    <div className="bg-white rounded-2xl max-w-md w-full border border-[#E8E6DF] shadow-2xl p-6 overflow-hidden">
                        <div className="flex items-start gap-4">
                            <div className="h-10 w-10 rounded-full bg-red-50 flex items-center justify-center text-red-600 flex-shrink-0">
                                <ShieldAlert className="h-5 w-5" />
                            </div>
                            <div>
                                <h3 className="text-[16px] font-bold text-ink leading-tight">Delete User Account</h3>
                                <p className="text-[13px] text-[#8C92AC] mt-2 leading-relaxed">
                                    Are you sure you want to delete <span className="font-bold text-ink">{selectedUser.name}</span>? This action cannot be undone and will delete all user enrollments and progress logs.
                                </p>
                            </div>
                        </div>
                        <div className="flex justify-end gap-3 mt-6">
                            <button
                                onClick={() => setDeleteModalOpen(false)}
                                className="px-4 py-2 border border-[#E8E6DF] rounded-xl text-[12px] font-bold hover:bg-[#FAFAF8] text-ink transition-all"
                            >
                                Cancel
                            </button>
                            <button
                                onClick={handleDelete}
                                className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-xl text-[12px] font-bold transition-all"
                            >
                                Delete Account
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </AdminLayout>
    );
}
