// import { Fragment } from 'react';
// import { Link, useNavigate } from 'react-router-dom';
// import { DataTable, DataTableSortStatus } from 'mantine-datatable';
// import { useEffect, useState } from 'react';
// import Tippy from '@tippyjs/react';
// import 'tippy.js/dist/tippy.css';
// import sortBy from 'lodash/sortBy';
// import { useDispatch, useSelector } from 'react-redux';
// import { IRootState } from '../../store';
// import { setPageTitle } from '../../store/themeConfigSlice';
// import Swal from 'sweetalert2';
// import { showMessage } from '../../general';
// import { deleteUser, updatePassword, viewUser } from '../../API';
// import { Modal } from '@mantine/core';
// import { Dialog, Transition } from '@headlessui/react';
// import { hasAccess } from '../../../../../utils/hasAccess';

// const UserManagement = () => {
//     const dispatch = useDispatch();
//     const navigate = useNavigate();

//     const PAGE_SIZES = [10, 20, 30, 50, 100];
//     const [page, setPage] = useState(1);
//     const [pageSize, setPageSize] = useState(PAGE_SIZES[0]);
//     const [initialRecords, setInitialRecords] = useState<any[]>([]);
//     const [recordsData, setRecordsData] = useState<any[]>([]);
//     const [totalRecords, setTotalRecords] = useState(0);
//     const [search, setSearch] = useState('');
//     const [sortStatus, setSortStatus] = useState<DataTableSortStatus>({ columnAccessor: 'name', direction: 'asc' });
//     const [loading, setLoading] = useState(false);
//     const [changePasswordModalOpen, setChangePasswordModalOpen] = useState(false);
//     const [selectedUser, setSelectedUser] = useState(null);
//     const [showPassword, setShowPassword] = useState(false);
//     const [passwordForm, setPasswordForm] = useState({ newPassword: '', confirmPassword: '' });


//     const isRtl = useSelector((state: IRootState) => state.themeConfig.rtlClass) === 'rtl';

//     const permissions = JSON.parse(localStorage.getItem("permissions") || "[]");
//     const userType = localStorage.getItem('userType')

//     // console.log("User Permissons", permissions)


//     const fetchUsers = async () => {
//         setLoading(true);
//         try {

//             const response = await viewUser()

//             console.log('fetch user response ', response.data)

//             if (response.status == true) {

//                 const formatted = response.data.map((user: any, i: number) => ({
//                     id: i + 1,
//                     _id: user._id,
//                     name: capitalize(user.name),
//                     email: user.email,
//                     role: capitalize(user.role),

//                     createdAt: user.created_at, // convert snake_case to camelCase
//                 }));

//                 setInitialRecords(formatted)
//                 setTotalRecords(formatted.length)

//             }


//         } catch (err) {
//             console.error(err);
//         } finally {
//             setLoading(false);
//         }
//     };

//     useEffect(() => {
//         dispatch(setPageTitle('User Management'));
//         fetchUsers();
//     }, []);

//     useEffect(() => setPage(1), [pageSize]);

//     useEffect(() => {
//         let sorted = sortBy(initialRecords, sortStatus.columnAccessor);
//         sorted = sortStatus.direction === 'desc' ? sorted.reverse() : sorted;

//         const filtered = sorted.filter(item =>
//             (item.name || '').toLowerCase().includes(search.toLowerCase()) ||
//             (item.email || '').toLowerCase().includes(search.toLowerCase()) ||
//             (item.role || '').toLowerCase().includes(search.toLowerCase()) ||
//             (item.status || '').toLowerCase().includes(search.toLowerCase())
//         );

//         const from = (page - 1) * pageSize;
//         const to = from + pageSize;
//         setRecordsData(filtered.slice(from, to));
//         setTotalRecords(filtered.length);
//     }, [page, pageSize, search, sortStatus, initialRecords]);



//     const deleteUserData = async (userId: string) => {

//         try {

//             const result = await Swal.fire({
//                 title: 'Are you sure?',
//                 text: 'This role will be permanently deleted!',
//                 icon: 'warning',
//                 showCancelButton: true,
//                 confirmButtonColor: '#d33',
//                 cancelButtonColor: '#3085d6',
//                 confirmButtonText: 'Yes, delete it!',
//             });

//             if (result.isConfirmed) {
//                 setLoading(true);
//                 const data = await deleteUser(userId)

//                 if (data.status == true) {

//                     Swal.fire({
//                         title: 'User Deleted!',
//                         text: `${data.message}`,
//                         icon: 'success',
//                         confirmButtonText: 'OK'
//                     });



//                     fetchUsers()

//                 }
//             }





//         } catch (error) {
//             Swal.fire({
//                 title: 'Error!',
//                 text: `${error.message}`,
//                 icon: 'error',
//                 confirmButtonText: 'OK'
//             });

//         }



//     };
//     const handlePasswordFormChange = (e: React.ChangeEvent<HTMLInputElement>) => {
//         const { name, value } = e.target;
//         setPasswordForm((prev) => ({ ...prev, [name]: value }));
//     };

//     const handlePasswordModal = (row) => {
//         console.log("passoword row", row)
//         setSelectedUser(row); // or row._id, depending on how you're handling user
//         setChangePasswordModalOpen(true);
//     }


//     const submitUpdatePassoerd = async () => {
//         try {

//             const payload = {
//                 id: selectedUser._id,
//                 password: passwordForm.newPassword
//             }
//             const resposne = await updatePassword(payload)

//             if (resposne.status == true) {
//                 Swal.fire({
//                     title: 'Password Updated!',
//                     text: `${resposne.message}`,
//                     icon: 'success',
//                     confirmButtonText: 'OK'
//                 });
//             }

//         } catch (error) {
//             console.log('error while update password', error)
//             Swal.fire({
//                 title: 'Error!',
//                 text: `${error.message}`,
//                 icon: 'error',
//                 confirmButtonText: 'OK'
//             })

//         }
//     }




//     return (
//         <div>
//             <div className="relative h-5">
//                 {hasAccess(permissions, "Users", "add") && (
//                     <Link
//                         className="absolute top-0 right-0 bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-700"
//                         to="/users/adduser"
//                     >
//                         Add User
//                     </Link>
//                 )}
//             </div>

//             <div className="panel mt-6">
//                 <div className="flex md:items-center md:flex-row flex-col mb-5 gap-5">
//                     <h5 className="font-semibold text-lg dark:text-white-light">Users</h5>
//                     <div className="ltr:ml-auto rtl:mr-auto">
//                         <input
//                             type="text"
//                             className="form-input w-auto"
//                             placeholder="Search..."
//                             value={search}
//                             onChange={(e) => setSearch(e.target.value)}
//                         />
//                     </div>
//                 </div>

//                 {loading ? (
//                     <div className="flex justify-center items-center h-20 mt-4">
//                         <div className="w-12 h-12 border-t-4 border-blue-500 border-solid rounded-full animate-spin"></div>
//                     </div>
//                 ) : (
//                     <div className="datatables">
//                         <DataTable
//                             highlightOnHover
//                             className="whitespace-nowrap table-hover"
//                             records={recordsData}
//                             columns={[
//                                 { accessor: 'name', title: 'Name', sortable: true },
//                                 { accessor: 'email', title: 'Email', sortable: true },
//                                 { accessor: 'role', title: 'Role', sortable: true },

//                                 {
//                                     accessor: 'createdAt',
//                                     title: 'Created At',
//                                     sortable: true,
//                                     render: ({ createdAt }) => new Date(createdAt).toLocaleString()
//                                 },
//                                 {
//                                     accessor: 'action',
//                                     title: 'Action',
//                                     titleClassName: '!text-center',
//                                     render: (row) => (
//                                         <div className="flex items-center w-max mx-auto gap-2">
//                                             <Link
//                                                 to={`/users/viewuser/${row._id}`}
//                                             >
//                                                 <Tippy content="View">
//                                                     <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
//                                                         <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
//                                                         <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
//                                                     </svg>
//                                                 </Tippy>
//                                             </Link>
//                                             {
//                                                 hasAccess(permissions, "Users", "edit") && (
//                                                     <Link to={`/users/edituser/${row._id}`}>
//                                                         <Tippy content="Edit">
//                                                             <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" >
//                                                                 <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
//                                                             </svg>
//                                                         </Tippy>
//                                                     </Link>
//                                                 )
//                                             }

//                                             {
//                                                 hasAccess(permissions, "Users", "delete") && (
//                                                     <Tippy content="Delete">
//                                                         <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" onClick={() => deleteUserData(row._id)}>
//                                                             <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
//                                                         </svg>
//                                                     </Tippy>
//                                                 )
//                                             }

//                                             {
//                                                 userType == 'admin' && (
//                                                     <button
//                                                         className="p-1 text-yellow-600 hover:text-yellow-800"
//                                                         onClick={() => {
//                                                             handlePasswordModal(row)
//                                                         }}
//                                                     >
//                                                         <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
//                                                             <path
//                                                                 fillRule="evenodd"
//                                                                 d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z"
//                                                                 clipRule="evenodd"
//                                                             />
//                                                         </svg>
//                                                     </button>
//                                                 )
//                                             }





//                                         </div>
//                                     ),
//                                 },
//                             ]}
//                             totalRecords={totalRecords}
//                             recordsPerPage={pageSize}
//                             page={page}
//                             onPageChange={setPage}
//                             recordsPerPageOptions={PAGE_SIZES}
//                             onRecordsPerPageChange={setPageSize}
//                             sortStatus={sortStatus}
//                             onSortStatusChange={setSortStatus}
//                             minHeight={200}
//                             paginationText={({ from, to, totalRecords }) => `Showing ${from} to ${to} of ${totalRecords} entries`}
//                         />
//                     </div>
//                 )}
//             </div>

//             <Transition appear show={changePasswordModalOpen} as={Fragment}>
//                 <Dialog as="div" open={changePasswordModalOpen} onClose={() => setChangePasswordModalOpen(false)}>
//                     <Transition.Child
//                         as={Fragment}
//                         enter="ease-out duration-300"
//                         enterFrom="opacity-0"
//                         enterTo="opacity-100"
//                         leave="ease-in duration-200"
//                         leaveFrom="opacity-100"
//                         leaveTo="opacity-0"
//                     >
//                         <div className="fixed inset-0 bg-black/60 z-[998]" />
//                     </Transition.Child>

//                     <div className="fixed inset-0 z-[999] overflow-y-auto">
//                         <div className="flex min-h-screen items-start justify-center px-4 py-8">
//                             <Transition.Child
//                                 as={Fragment}
//                                 enter="ease-out duration-300"
//                                 enterFrom="opacity-0 scale-95"
//                                 enterTo="opacity-100 scale-100"
//                                 leave="ease-in duration-200"
//                                 leaveFrom="opacity-100 scale-100"
//                                 leaveTo="opacity-0 scale-95"
//                             >
//                                 <Dialog.Panel className="panel w-full max-w-lg overflow-hidden rounded-lg border-0 p-0 text-black dark:text-white-dark">
//                                     {/* Header */}
//                                     <div className="flex items-center justify-between bg-[#fbfbfb] px-5 py-3 dark:bg-[#121c2c]">
//                                         <div className="text-lg font-bold">Change Password for {selectedUser?.name || 'User'}</div>
//                                         <button type="button" className="text-white-dark hover:text-dark" onClick={() => setChangePasswordModalOpen(false)}>
//                                             <svg
//                                                 xmlns="http://www.w3.org/2000/svg"
//                                                 width="20"
//                                                 height="20"
//                                                 viewBox="0 0 24 24"
//                                                 fill="none"
//                                                 stroke="currentColor"
//                                                 strokeWidth="1.5"
//                                                 strokeLinecap="round"
//                                                 strokeLinejoin="round"
//                                             >
//                                                 <line x1="18" y1="6" x2="6" y2="18"></line>
//                                                 <line x1="6" y1="6" x2="18" y2="18"></line>
//                                             </svg>
//                                         </button>
//                                     </div>

//                                     {/* Form Body */}
//                                     <div className="p-5">
//                                         <form onSubmit={submitUpdatePassoerd} >
//                                             <div className="space-y-4">
//                                                 <div className="relative">
//                                                     <label className="block text-sm font-medium mb-1">New Password</label>
//                                                     <input
//                                                         type={showPassword ? 'text' : 'password'}
//                                                         name="newPassword"
//                                                         value={passwordForm.newPassword}
//                                                         onChange={handlePasswordFormChange}
//                                                         className="form-input w-full pr-10"
//                                                         required
//                                                         minLength={6}
//                                                     />
//                                                 </div>
//                                                 <div className="relative">
//                                                     <label className="block text-sm font-medium mb-1">Confirm Password</label>
//                                                     <input
//                                                         type={showPassword ? 'text' : 'password'}
//                                                         name="confirmPassword"
//                                                         value={passwordForm.confirmPassword}
//                                                         onChange={handlePasswordFormChange}
//                                                         className="form-input w-full pr-10"
//                                                         required
//                                                         minLength={6}
//                                                     />
//                                                     <button
//                                                         type="button"
//                                                         className="absolute right-3 bottom-2 text-gray-500 hover:text-gray-700"
//                                                         onClick={() => setShowPassword(!showPassword)}
//                                                     >
//                                                         {showPassword ? (
//                                                             <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
//                                                                 <path d="M10 12a2 2 0 100-4 2 2 0 000 4z" />
//                                                                 <path
//                                                                     fillRule="evenodd"
//                                                                     d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z"
//                                                                     clipRule="evenodd"
//                                                                 />
//                                                             </svg>
//                                                         ) : (
//                                                             <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
//                                                                 <path
//                                                                     fillRule="evenodd"
//                                                                     d="M3.707 2.293a1 1 0 00-1.414 1.414l14 14a1 1 0 001.414-1.414l-1.473-1.473A10.014 10.014 0 0019.542 10C18.268 5.943 14.478 3 10 3a9.958 9.958 0 00-4.512 1.074l-1.78-1.781zm4.261 4.26l1.514 1.515a2.003 2.003 0 012.45 2.45l1.514 1.514a4 4 0 00-5.478-5.478z"
//                                                                     clipRule="evenodd"
//                                                                 />
//                                                                 <path d="M12.454 16.697L9.75 13.992a4 4 0 01-3.742-3.741L2.335 6.578A9.98 9.98 0 00.458 10c1.274 4.057 5.065 7 9.542 7 .847 0 1.669-.105 2.454-.303z" />
//                                                             </svg>
//                                                         )}
//                                                     </button>
//                                                 </div>
//                                                 <div className="flex justify-end space-x-2 pt-4">
//                                                     <button
//                                                         type="button"
//                                                         onClick={() => setChangePasswordModalOpen(false)}
//                                                         className="btn btn-outline"
//                                                     >
//                                                         Cancel
//                                                     </button>
//                                                     <button
//                                                         type="submit"
//                                                         className="btn btn-primary"
//                                                         disabled={
//                                                             !passwordForm.newPassword ||
//                                                             !passwordForm.confirmPassword ||
//                                                             passwordForm.newPassword !== passwordForm.confirmPassword
//                                                         }
//                                                     >
//                                                         Change Password
//                                                     </button>
//                                                 </div>
//                                             </div>
//                                         </form>
//                                     </div>
//                                 </Dialog.Panel>
//                             </Transition.Child>
//                         </div>
//                     </div>
//                 </Dialog>
//             </Transition>
//         </div>
//     );
// };

// function capitalize(text: string): string {
//     return text ? text.charAt(0).toUpperCase() + text.slice(1).toLowerCase() : '';
// }

// export default UserManagement;



import { Fragment } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { DataTable, DataTableSortStatus } from 'mantine-datatable';
import { useEffect, useState } from 'react';
import Tippy from '@tippyjs/react';
import 'tippy.js/dist/tippy.css';
import sortBy from 'lodash/sortBy';
import { useDispatch, useSelector } from 'react-redux';
import { IRootState } from '../../store';
import { setPageTitle } from '../../store/themeConfigSlice';
import Swal from 'sweetalert2';
import { showMessage } from '../../general';
import { deleteUser, updatePassword, viewUser } from '../../API';
import { Dialog, Transition } from '@headlessui/react';
import { hasAccess } from '../../../../../utils/hasAccess';
import { FaEye, FaEdit, FaTrash, FaKey, FaUserPlus } from 'react-icons/fa';
import { HiEye, HiEyeOff } from 'react-icons/hi';
import { useLoader } from '../../store/LoaderProvider';

const UserManagement = () => {
    const dispatch = useDispatch();
    const navigate = useNavigate();
    const isDark = useSelector((state: IRootState) => state.themeConfig.theme === 'dark' || state.themeConfig.isDarkMode);

    const PAGE_SIZES = [10, 20, 30, 50, 100];
    const [page, setPage] = useState(1);
    const [pageSize, setPageSize] = useState(PAGE_SIZES[0]);
    const [initialRecords, setInitialRecords] = useState<any[]>([]);
    const [recordsData, setRecordsData] = useState<any[]>([]);
    const [totalRecords, setTotalRecords] = useState(0);
    const [search, setSearch] = useState('');
    const [sortStatus, setSortStatus] = useState<DataTableSortStatus>({ columnAccessor: 'name', direction: 'asc' });
    const [loading, setLoading] = useState(false);
    const [changePasswordModalOpen, setChangePasswordModalOpen] = useState(false);
    const [selectedUser, setSelectedUser] = useState<any>(null);
    const [showPassword, setShowPassword] = useState(false);
    const [passwordForm, setPasswordForm] = useState({ newPassword: '', confirmPassword: '' });
       const { showLoader, hideLoader } = useLoader();

    const isRtl = useSelector((state: IRootState) => state.themeConfig.rtlClass) === 'rtl';
    const permissions = JSON.parse(localStorage.getItem("permissions") || "[]");
    const userType = localStorage.getItem('userType');

    const fetchUsers = async () => {
        showLoader( );
        try {
            const response = await viewUser();
            if (response.status == true) {
                const formatted = response.data.map((user: any, i: number) => {
                    // Handle timestamp conversion - if it's an integer timestamp (unix timestamp)
                    let createdAtFormatted = 'N/A';
                    if (user.created_at) {
                        // If it's already an integer (unix timestamp in seconds)
                        if (typeof user.created_at === 'number') {
                            createdAtFormatted = new Date(user.created_at * 1000).toLocaleDateString('en-US', {
                                year: 'numeric',
                                month: 'short',
                                day: 'numeric'
                            });
                        } 
                        // If it's still a MongoDB date object or string
                        else if (typeof user.created_at === 'object' && user.created_at.$date) {
                            createdAtFormatted = new Date(user.created_at.$date).toLocaleDateString('en-US', {
                                year: 'numeric',
                                month: 'short',
                                day: 'numeric'
                            });
                        }
                        // If it's a string date
                        else if (typeof user.created_at === 'string') {
                            createdAtFormatted = new Date(user.created_at).toLocaleDateString('en-US', {
                                year: 'numeric',
                                month: 'short',
                                day: 'numeric'
                            });
                        }
                    }
                    
                    return {
                        id: i + 1,
                        _id: user._id,
                        name: capitalize(user.name),
                        email: user.email,
                        role: capitalize(user.role),
                        createdAt: createdAtFormatted,
                        createdAtRaw: user.created_at // Keep raw for sorting
                    };
                });
                setInitialRecords(formatted);
                setTotalRecords(formatted.length);
            }
        } catch (err) {
            console.error(err);
        } finally {
            hideLoader( );
        }
    };

    useEffect(() => {
        dispatch(setPageTitle('User Management'));
        fetchUsers();
    }, []);

    useEffect(() => setPage(1), [pageSize]);

    useEffect(() => {
        let sorted = sortBy(initialRecords, sortStatus.columnAccessor);
        sorted = sortStatus.direction === 'desc' ? sorted.reverse() : sorted;

        const filtered = sorted.filter(item =>
            (item.name || '').toLowerCase().includes(search.toLowerCase()) ||
            (item.email || '').toLowerCase().includes(search.toLowerCase()) ||
            (item.role || '').toLowerCase().includes(search.toLowerCase())
        );

        const from = (page - 1) * pageSize;
        const to = from + pageSize;
        setRecordsData(filtered.slice(from, to));
        setTotalRecords(filtered.length);
    }, [page, pageSize, search, sortStatus, initialRecords]);

    const deleteUserData = async (userId: string) => {
        try {
            const result = await Swal.fire({
                title: 'Are you sure?',
                text: 'This user will be permanently deleted!',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#e7515a',
                cancelButtonColor: '#2196f3',
                confirmButtonText: 'Yes, delete it!',
                 customClass: {
    confirmButton: 'bg-[#5c4d2f] text-white px-4 py-2 rounded hover:bg-[#4a3e27]',
    cancelButton: 'px-6 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-secondary dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors',
    actions: 'space-x-3' // adds gap between confirm & cancel buttons
},
buttonsStyling: false 
            });

            if (result.isConfirmed) {
                showLoader( );
                const data = await deleteUser(userId);
                if (data.status == true) {
                    showMessage(data.message, data.status);
                    fetchUsers();
                }
            }
        } catch (error) {
            showMessage(error.message, 'error');
        } finally {
            hideLoader( );
        }
    };

    const handlePasswordFormChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        setPasswordForm((prev) => ({ ...prev, [name]: value }));
    };

    const handlePasswordModal = (row: any) => {
        setSelectedUser(row);
        setChangePasswordModalOpen(true);
    };

    const submitUpdatePassword = async () => {
        try {
            if (passwordForm.newPassword !== passwordForm.confirmPassword) {
                showMessage("Passwords don't match", 'error');
                return;
            }

            const payload = {
                id: selectedUser._id,
                password: passwordForm.newPassword
            };
            const response = await updatePassword(payload);
            if (response.status == true) {
                showMessage(response.message, response.status);
                setChangePasswordModalOpen(false);
                setPasswordForm({ newPassword: '', confirmPassword: '' });
            }
        } catch (error) {
            showMessage(error.message, 'error');
        }
    };

    return (
        <div className="relative">
            <div className="panel  ">
                <div className="flex md:items-center md:flex-row flex-col mb-5 gap-5">
                    <div>
                        <h5 className="font-semibold text-lg dark:text-white-light">User Management</h5>
                        {/* <p className="text-sm text-gray-500 dark:text-gray-400">Manage all system users and permissions</p> */}
                    </div>
                    <div className="ltr:ml-auto rtl:mr-auto flex items-center gap-4">
                        <div className="relative flex-1">
                            <input
                                type="text"
                                className="form-input w-full pl-10 pr-4 py-2 rounded-lg border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 dark:focus:ring-primary-400 dark:focus:border-primary-400 transition-all duration-200"
                                placeholder="Search users..."
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                            />
                            <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                                <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                                </svg>
                            </div>
                        </div>

                        {hasAccess(permissions, "Users", "add") && (
                            <Link
                                className="btn btn-primary rounded-lg px-4 py-2 text-white bg-primary-DEFAULT hover:bg-primary-light border-primary-DEFAULT hover:border-primary-light transition-all duration-200 shadow-primary hover:shadow-primary-lg flex items-center gap-2"
                                to="/users/adduser"
                            >
                                <FaUserPlus className="text-lg" /> Add User
                            </Link>
                        )}
                    </div>
                </div>

                {loading ? (
                      <div className="fixed inset-0 flex justify-center items-center bg-black bg-opacity-50 z-[9999]">
            <div className="w-16 h-16 border-t-4 border-primary-DEFAULT border-solid rounded-full animate-spin"></div>
          </div>
                ) : (
                    <div className="datatables">
                        <DataTable
                            highlightOnHover
                            className="whitespace-nowrap table-hover rounded-lg overflow-hidden"
                            records={recordsData}
                            columns={[
                                {
                                    accessor: 'name',
                                    title: 'Name',
                                    sortable: true,
                                    render: ({ name }) => (
                                        <span className="font-medium dark:text-white-light">{name}</span>
                                    )
                                },
                                {
                                    accessor: 'email',
                                    title: 'Email',
                                    sortable: true,
                                    render: ({ email }) => (
                                        <span className="text-gray-600 dark:text-gray-300">{email}</span>
                                    )
                                },
                                {
                                    accessor: 'role',
                                    title: 'Role',
                                    sortable: true,
                                    render: ({ role }) => (
                                        <span className={`px-2 py-1 rounded-md text-sm font-medium ${role === 'Admin'
                                            ? 'bg-primary/10 dark:bg-primary-dark-light text-primary-DEFAULT dark:text-primary-light'
                                            : 'bg-secondary/10 dark:bg-secondary-dark-light text-secondary-DEFAULT dark:text-secondary-light'
                                            }`}>
                                            {role}
                                        </span>
                                    )
                                },
                                {
                                    accessor: 'createdAt',
                                    title: 'Created At',
                                    sortable: true,
                                    render: ({ createdAt }) => (
                                        <span className="text-gray-600 dark:text-gray-300">{createdAt}</span>
                                    )
                                },
                                {
                                    accessor: 'action',
                                    title: 'Actions',
                                    titleClassName: '!text-center',
                                    render: (row) => (
                                        <div className="flex items-center w-max mx-auto ">
                                            <Tippy content="View">
                                                <Link
                                                    to={`/users/viewuser/${row._id}`}
                                                    className="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-200"
                                                >
                                                    <svg className="w-5 h-5 text-gray-500 hover:text-primary dark:text-gray-300 dark:hover:text-primary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                                    </svg>
                                                </Link>
                                            </Tippy>

                                            {hasAccess(permissions, "Users", "edit") && (
                                                <Tippy content="Edit">
                                                    <Link
                                                        to={`/users/edituser/${row._id}`}
                                                        className="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-200"
                                                    >
                                                        <svg className="w-5 h-5 text-gray-500 hover:text-primary dark:text-gray-300 dark:hover:text-primary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                                        </svg>
                                                    </Link>
                                                </Tippy>
                                            )}

                                            {hasAccess(permissions, "Users", "delete") && (
                                                <Tippy content="Delete">
                                                    <button
                                                        className="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-200"
                                                        onClick={() => deleteUserData(row._id)}
                                                    >
                                                        <svg className="w-5 h-5 text-gray-500 hover:text-danger dark:text-gray-300 dark:hover:text-danger" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                                        </svg>                                                    </button>
                                                </Tippy>
                                            )}

                                            {userType == 'admin' && (
                                                <Tippy content="Change Password">
                                                    <button
                                                        className="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-200"
                                                        onClick={() => handlePasswordModal(row)}
                                                    >
                                                        <FaKey className="w-5 h-5 text-gray-500 hover:text-primary dark:text-gray-300 dark:hover:text-primary" />
                                                    </button>
                                                </Tippy>
                                            )}
                                        </div>
                                    ),
                                },
                            ]}
                            totalRecords={totalRecords}
                            recordsPerPage={pageSize}
                            page={page}
                            onPageChange={setPage}
                            recordsPerPageOptions={PAGE_SIZES}
                            onRecordsPerPageChange={setPageSize}
                            sortStatus={sortStatus}
                            onSortStatusChange={setSortStatus}
                            minHeight={200}
                            rowClassName={(record) =>
                                `transition-colors duration-100 ${isDark ? 'hover:bg-gray-700' : 'hover:bg-gray-50'}`
                            }
                            paginationText={({ from, to, totalRecords }) => (
                                <span className="dark:text-white-light">
                                    Showing {from} to {to} of {totalRecords} entries
                                </span>
                            )}
                        />
                    </div>
                )}
            </div>

            {/* Change Password Modal */}
            <Transition appear show={changePasswordModalOpen} as={Fragment}>
                <Dialog as="div" open={changePasswordModalOpen} onClose={() => setChangePasswordModalOpen(false)}>
                    <Transition.Child
                        as={Fragment}
                        enter="ease-out duration-300"
                        enterFrom="opacity-0"
                        enterTo="opacity-100"
                        leave="ease-in duration-200"
                        leaveFrom="opacity-100"
                        leaveTo="opacity-0"
                    >
                        <div className="fixed inset-0 bg-black/60 z-[998]" />
                    </Transition.Child>

                    <div className="fixed inset-0 z-[999] overflow-y-auto">
                        <div className="flex min-h-screen items-center justify-center p-4">
                            <Transition.Child
                                as={Fragment}
                                enter="ease-out duration-300"
                                enterFrom="opacity-0 scale-95"
                                enterTo="opacity-100 scale-100"
                                leave="ease-in duration-200"
                                leaveFrom="opacity-100 scale-100"
                                leaveTo="opacity-0 scale-95"
                            >
                                <Dialog.Panel className={`panel w-full max-w-lg overflow-hidden rounded-lg border-0 p-0 ${isDark ? 'bg-gray-800' : 'bg-white'} shadow-lg`}>
                                    <div className={`flex items-center justify-between px-5 py-3 ${isDark ? 'bg-gray-700' : 'bg-gray-50'}`}>
                                        <div className="text-lg font-bold text-primary-DEFAULT dark:text-primary-light">
                                            Change Password for {selectedUser?.name || 'User'}
                                        </div>
                                        <button
                                            type="button"
                                            className="text-gray-500 hover:text-gray-700 dark:hover:text-primary"
                                            onClick={() => setChangePasswordModalOpen(false)}
                                        >
                                            <svg
                                                xmlns="http://www.w3.org/2000/svg"
                                                width="20"
                                                height="20"
                                                viewBox="0 0 24 24"
                                                fill="none"
                                                stroke="currentColor"
                                                strokeWidth="1.5"
                                                strokeLinecap="round"
                                                strokeLinejoin="round"
                                            >
                                                <line x1="18" y1="6" x2="6" y2="18"></line>
                                                <line x1="6" y1="6" x2="18" y2="18"></line>
                                            </svg>
                                        </button>
                                    </div>

                                    <div className="p-5">
                                        <form onSubmit={(e) => { e.preventDefault(); submitUpdatePassword(); }}>
                                            <div className="space-y-4">
                                                <div className="relative">
                                                    <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">New Password</label>
                                                    <div className="relative">
                                                        <input
                                                            type={showPassword ? 'text' : 'password'}
                                                            name="newPassword"
                                                            value={passwordForm.newPassword}
                                                            onChange={handlePasswordFormChange}
                                                            className="form-input w-full pr-10 rounded-lg border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 dark:focus:ring-primary-400 dark:focus:border-primary-400 transition-all duration-200"
                                                            required
                                                            minLength={6}
                                                        />
                                                        <button
                                                            type="button"
                                                            className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 hover:text-gray-700 dark:hover:text-primary"
                                                            onClick={() => setShowPassword(!showPassword)}
                                                        >
                                                            {showPassword ? (
                                                                <HiEyeOff className="h-5 w-5" />
                                                            ) : (
                                                                <HiEye className="h-5 w-5" />
                                                            )}
                                                        </button>
                                                    </div>
                                                </div>
                                                <div className="relative">
                                                    <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Confirm Password</label>
                                                    <div className="relative">
                                                        <input
                                                            type={showPassword ? 'text' : 'password'}
                                                            name="confirmPassword"
                                                            value={passwordForm.confirmPassword}
                                                            onChange={handlePasswordFormChange}
                                                            className="form-input w-full pr-10 rounded-lg border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 dark:focus:ring-primary-400 dark:focus:border-primary-400 transition-all duration-200"
                                                            required
                                                            minLength={6}
                                                        />
                                                        <button
                                                            type="button"
                                                            className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 hover:text-gray-700 dark:hover:text-primary"
                                                            onClick={() => setShowPassword(!showPassword)}
                                                        >
                                                            {showPassword ? (
                                                                <HiEyeOff className="h-5 w-5" />
                                                            ) : (
                                                                <HiEye className="h-5 w-5" />
                                                            )}
                                                        </button>
                                                    </div>
                                                </div>
                                                <div className="flex justify-end space-x-3 pt-4">
                                                    <button
                                                        type="button"
                                                        onClick={() => setChangePasswordModalOpen(false)}
                                                          className="px-6 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-secondary dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
                                                    >
                                                        Cancel
                                                    </button>
                                                    <button
                                                        type="submit"
                                                        className="btn btn-primary rounded-lg px-4 py-2 text-white bg-primary-DEFAULT hover:bg-primary-light border-primary-DEFAULT hover:border-primary-light transition-all duration-200 shadow-primary hover:shadow-primary-lg"
                                                        disabled={
                                                            !passwordForm.newPassword ||
                                                            !passwordForm.confirmPassword ||
                                                            passwordForm.newPassword !== passwordForm.confirmPassword
                                                        }
                                                    >
                                                        Change Password
                                                    </button>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                </Dialog.Panel>
                            </Transition.Child>
                        </div>
                    </div>
                </Dialog>
            </Transition>
        </div>
    );
};

// function capitalize(text: string): string {
//     return text ? text.charAt(0).toUpperCase() + text.slice(1).toLowerCase() : '';
// }
function capitalize(text: string): string {
  if (!text) return '';

  return text
    .split(' ') // Split by spaces
    .map(word => 
      word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
    )
    .join(' '); // Join back into a single string
}


export default UserManagement;  