"use client";

import { useState } from "react";
import { useSelector } from "react-redux";
import { motion, AnimatePresence } from "framer-motion";
import {
    Search,
    CheckCircle,
    XCircle,
    MoreVertical,
    Filter,
    Download,
    Shield,
    User,
    Clock,
    ChevronLeft,
    ChevronRight,
    Eye,
} from "lucide-react";
import Layout from "@/app/components/Layout";
import { useGetUsersQuery, useVerifyUserMutation } from "@/redux/apis/adminApi";
import { selectCurrentUser } from "@/redux/slices/authSlice";

export default function UsersPage() {
    const [page, setPage] = useState(1);
    const [limit] = useState(10);
    const [search, setSearch] = useState("");
    const [roleFilter, setRoleFilter] = useState("");
    const [selectedUser, setSelectedUser] = useState<any>(null); // For detail view modal

    // Use the query with parameters
    const { data, isLoading, isError, refetch } = useGetUsersQuery({
        page,
        limit,
        search,
        role: roleFilter || undefined,
    });

    const [verifyUser] = useVerifyUserMutation();

    const handleVerify = async (userId: number, status: string) => {
        if (confirm(`Are you sure you want to mark this user as ${status}?`)) {
            try {
                await verifyUser({ userId, status }).unwrap();
                // Toast success message here
                refetch(); // Refresh the list
            } catch (error) {
                console.error("Failed to update status:", error);
                // Toast error message here
            }
        }
    };

    const statusColors = {
        verified: "bg-green-500/10 text-green-500",
        pending: "bg-yellow-500/10 text-yellow-500",
        rejected: "bg-red-500/10 text-red-500",
    };

    return (
        <Layout>
            <div className="p-6">
                <div className="max-w-[1600px] mx-auto">
                    {/* Header */}
                    <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6">
                        <div>
                            <h1 className="text-3xl font-bold text-gray-900">User Management</h1>
                            <p className="text-gray-600 mt-1">Manage all registered users and their verification status</p>
                        </div>
                        <div className="flex gap-3">
                            <button className="flex items-center gap-2 px-4 py-2 bg-white border border-gray-200 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors shadow-sm">
                                <Download className="w-4 h-4" />
                                <span>Export User Report</span>
                            </button>
                        </div>
                    </div>

                    {/* Filters */}
                    <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-6">
                        <div className="flex flex-col md:flex-row gap-4">
                            <div className="flex-1 relative">
                                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                                <input
                                    type="text"
                                    placeholder="Search users by name, email or phone..."
                                    value={search}
                                    onChange={(e) => setSearch(e.target.value)}
                                    className="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                                />
                            </div>
                            <div className="flex gap-4">
                                <div className="relative min-w-[180px]">
                                    <select
                                        value={roleFilter}
                                        onChange={(e) => setRoleFilter(e.target.value)}
                                        className="w-full pl-4 pr-10 py-2 border border-gray-200 rounded-lg text-gray-700 bg-white appearance-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                                    >
                                        <option value="">All Roles</option>
                                        <option value="user">User</option>
                                        <option value="admin">Admin</option>
                                    </select>
                                    <Filter className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Users Table */}
                    <div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                        <div className="overflow-x-auto">
                            <table className="w-full">
                                <thead className="bg-gray-50 border-b border-gray-200">
                                    <tr>
                                        <th className="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">User</th>
                                        <th className="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Role</th>
                                        <th className="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Verification</th>
                                        <th className="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Joined Date</th>
                                        <th className="px-6 py-3 text-right text-xs font-semibold text-gray-500 uppercase tracking-wider">Actions</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-200">
                                    {isLoading ? (
                                        <tr>
                                            <td colSpan={5} className="px-6 py-12 text-center text-gray-500">
                                                <div className="flex justify-center items-center gap-2">
                                                    <div className="w-5 h-5 border-2 border-blue-600 border-t-transparent rounded-full animate-spin" />
                                                    Loading users...
                                                </div>
                                            </td>
                                        </tr>
                                    ) : isError ? (
                                        <tr>
                                            <td colSpan={5} className="px-6 py-12 text-center text-red-600">
                                                Failed to load users. Please try again.
                                            </td>
                                        </tr>
                                    ) : data?.data && data.data.length > 0 ? (
                                        data.data.map((user) => (
                                            <motion.tr
                                                key={user.id}
                                                initial={{ opacity: 0 }}
                                                animate={{ opacity: 1 }}
                                                className="group hover:bg-gray-50 transition-colors"
                                            >
                                                <td className="px-6 py-4">
                                                    <div className="flex items-center gap-3">
                                                        <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center text-blue-700 font-bold border border-blue-200">
                                                            {user.name.charAt(0).toUpperCase()}
                                                        </div>
                                                        <div>
                                                            <p className="text-sm font-semibold text-gray-900">{user.name}</p>
                                                            <p className="text-xs text-gray-500">{user.email}</p>
                                                            {user.phone && <p className="text-xs text-gray-500">{user.phone}</p>}
                                                        </div>
                                                    </div>
                                                </td>
                                                <td className="px-6 py-4">
                                                    <span className="px-3 py-1 bg-gray-100 text-gray-700 rounded-full text-xs font-medium capitalize border border-gray-200">
                                                        {user.role}
                                                    </span>
                                                </td>
                                                <td className="px-6 py-4">
                                                    <div className="flex items-center gap-2">
                                                        {user.profileVerificationStatus === 'verified' && (
                                                            <span className="px-3 py-1 bg-green-100 text-green-700 rounded-full text-xs font-medium flex items-center gap-1">
                                                                <CheckCircle className="w-3 h-3" /> Verified
                                                            </span>
                                                        )}
                                                        {user.profileVerificationStatus === 'pending' && (
                                                            <span className="px-3 py-1 bg-yellow-100 text-yellow-700 rounded-full text-xs font-medium flex items-center gap-1">
                                                                <Clock className="w-3 h-3" /> Pending
                                                            </span>
                                                        )}
                                                        {user.profileVerificationStatus === 'rejected' && (
                                                            <span className="px-3 py-1 bg-red-100 text-red-700 rounded-full text-xs font-medium flex items-center gap-1">
                                                                <XCircle className="w-3 h-3" /> Rejected
                                                            </span>
                                                        )}
                                                        {(!user.profileVerificationStatus) && (
                                                            <span className="px-3 py-1 bg-gray-100 text-gray-500 rounded-full text-xs font-medium border border-gray-200">
                                                                Not Submitted
                                                            </span>
                                                        )}
                                                    </div>
                                                </td>
                                                <td className="px-6 py-4">
                                                    <div className="flex items-center gap-2 text-sm text-gray-600">
                                                        <Clock className="w-4 h-4 text-gray-400" />
                                                        {new Date(user.createdAt).toLocaleDateString()}
                                                    </div>
                                                </td>
                                                <td className="px-6 py-4 text-right">
                                                    <div className="flex items-center justify-end gap-2">
                                                        <button
                                                            onClick={() => setSelectedUser(user)}
                                                            className="p-2 text-gray-500 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                                                            title="View Details"
                                                        >
                                                            <Eye className="w-4 h-4" />
                                                        </button>
                                                        {user.profileVerificationStatus === 'pending' && (
                                                            <>
                                                                <button
                                                                    onClick={() => handleVerify(user.id, 'verified')}
                                                                    className="p-2 text-green-600 hover:bg-green-50 rounded-lg transition-colors"
                                                                    title="Approve"
                                                                >
                                                                    <CheckCircle className="w-4 h-4" />
                                                                </button>
                                                                <button
                                                                    onClick={() => handleVerify(user.id, 'rejected')}
                                                                    className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                                                                    title="Reject"
                                                                >
                                                                    <XCircle className="w-4 h-4" />
                                                                </button>
                                                            </>
                                                        )}
                                                    </div>
                                                </td>
                                            </motion.tr>
                                        ))
                                    ) : (
                                        <tr>
                                            <td colSpan={5} className="px-6 py-12 text-center text-gray-500">
                                                <div className="flex flex-col items-center gap-3">
                                                    <User className="w-12 h-12 text-gray-400" />
                                                    <p>No users found matching your search.</p>
                                                </div>
                                            </td>
                                        </tr>
                                    )}
                                </tbody>
                            </table>
                        </div>

                        {/* Pagination */}
                        {data?.pagination && data.pagination.pages > 1 && (
                            <div className="px-6 py-4 border-t border-gray-200 flex items-center justify-between bg-gray-50">
                                <p className="text-sm text-gray-600">
                                    Showing {((page - 1) * limit) + 1} to {Math.min(page * limit, data.pagination.total)} of {data.pagination.total} users
                                </p>
                                <div className="flex gap-2">
                                    <button
                                        onClick={() => setPage(p => Math.max(1, p - 1))}
                                        disabled={page === 1}
                                        className="p-2 border border-gray-300 rounded-lg text-gray-600 hover:bg-white disabled:opacity-50 disabled:cursor-not-allowed transition-colors bg-white shadow-sm"
                                    >
                                        <ChevronLeft className="w-4 h-4" />
                                    </button>
                                    <button
                                        onClick={() => setPage(p => Math.min(data.pagination!.pages, p + 1))}
                                        disabled={page === data.pagination.pages}
                                        className="p-2 border border-gray-300 rounded-lg text-gray-600 hover:bg-white disabled:opacity-50 disabled:cursor-not-allowed transition-colors bg-white shadow-sm"
                                    >
                                        <ChevronRight className="w-4 h-4" />
                                    </button>
                                </div>
                            </div>
                        )}
                    </div>

                    {/* User Search Detail Modal */}
                    <AnimatePresence>
                        {selectedUser && (
                            <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/20 backdrop-blur-sm">
                                <motion.div
                                    initial={{ opacity: 0, scale: 0.95 }}
                                    animate={{ opacity: 1, scale: 1 }}
                                    exit={{ opacity: 0, scale: 0.95 }}
                                    className="bg-white border border-gray-200 rounded-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto shadow-2xl"
                                >
                                    <div className="sticky top-0 bg-white border-b border-gray-200 p-6 flex items-center justify-between z-10">
                                        <h2 className="text-xl font-bold text-gray-900">User Details</h2>
                                        <button
                                            onClick={() => setSelectedUser(null)}
                                            className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
                                        >
                                            <XCircle className="w-6 h-6" />
                                        </button>
                                    </div>
                                    <div className="p-6 space-y-6">
                                        <div className="flex items-center gap-4">
                                            <div className="w-20 h-20 rounded-full bg-blue-100 flex items-center justify-center text-blue-700 text-2xl font-bold border border-blue-200">
                                                {selectedUser.name.charAt(0).toUpperCase()}
                                            </div>
                                            <div>
                                                <h3 className="text-xl font-bold text-gray-900">{selectedUser.name}</h3>
                                                <p className="text-gray-600">{selectedUser.email}</p>
                                                <p className="text-gray-600">{selectedUser.phone || 'No phone number'}</p>
                                                <div className="mt-2 flex gap-2">
                                                    <span className="px-3 py-1 bg-gray-100 text-gray-700 rounded-full text-xs font-medium capitalize border border-gray-200">
                                                        {selectedUser.role}
                                                    </span>
                                                    <span className={`px-3 py-1 rounded-full text-xs font-medium border ${selectedUser.isActive
                                                        ? 'bg-green-100 text-green-700 border-green-200'
                                                        : 'bg-red-100 text-red-700 border-red-200'
                                                        }`}>
                                                        {selectedUser.isActive ? 'Active' : 'Inactive'}
                                                    </span>
                                                </div>
                                            </div>
                                        </div>

                                        <div className="grid grid-cols-2 gap-4">
                                            <div className="p-4 bg-gray-50 rounded-xl border border-gray-200">
                                                <p className="text-xs text-gray-500 mb-1">Joined Date</p>
                                                <p className="text-sm font-medium text-gray-900">{new Date(selectedUser.createdAt).toLocaleDateString()}</p>
                                            </div>
                                            <div className="p-4 bg-gray-50 rounded-xl border border-gray-200">
                                                <p className="text-xs text-gray-500 mb-1">Profile Status</p>
                                                <p className="text-sm font-medium text-gray-900 capitalize">
                                                    {selectedUser.profileVerificationStatus || 'Not Submitted'}
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                    <div className="sticky bottom-0 bg-white border-t border-gray-200 p-6 flex justify-end gap-3">
                                        <button
                                            onClick={() => setSelectedUser(null)}
                                            className="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
                                        >
                                            Close
                                        </button>
                                        {selectedUser.profileVerificationStatus === 'pending' && (
                                            <>
                                                <button
                                                    onClick={() => {
                                                        handleVerify(selectedUser.id, 'rejected');
                                                        setSelectedUser(null);
                                                    }}
                                                    className="px-4 py-2 bg-red-50 text-red-600 hover:bg-red-100 border border-red-200 rounded-lg transition-colors"
                                                >
                                                    Reject Profile
                                                </button>
                                                <button
                                                    onClick={() => {
                                                        handleVerify(selectedUser.id, 'verified');
                                                        setSelectedUser(null);
                                                    }}
                                                    className="px-4 py-2 bg-green-600 text-white hover:bg-green-700 rounded-lg transition-colors shadow-sm"
                                                >
                                                    Approve Profile
                                                </button>
                                            </>
                                        )}
                                    </div>
                                </motion.div>
                            </div>
                        )}
                    </AnimatePresence>
                </div>
            </div>
        </Layout>
    );
}
