'use client';
import React, {useCallback, useEffect, useMemo, useState} from 'react';
import {toast} from "react-toastify";
import {useRouter} from "next/navigation";
import {debounce} from "next/dist/server/utils";
import {Input} from "@/components/ui/input";
import {Image} from "next/dist/client/image-component";
import Link from "next/link";
import {FaRegEdit} from "react-icons/fa";
import DeleteConfirmation from "@/components/common-ui/DeleteConfirmation";
import TablePagination from "@/components/common-ui/TablePagination";
interface Props {
    data: any
    deleteUser: (id: any) => Promise<any>
}

function UsersTable({data, deleteUser}: Props) {
    const pageNumber = (url: any) => {
        if (url === null) return;
        const urlObject = new URL(url);
        return urlObject.searchParams.get('page');
    }
    const Delete = async (id: any) => {
        const res = await deleteUser(id)
        if (res.success) {
            toast.success(res.message);
        } else if (!res.success) {
            toast.error(res.message);
            console.log(res.Status);
        }
    }
    const router = useRouter();
    const [searchTerm, setSearchTerm] = useState('');
    const handleSearch = useCallback((value: string) => router.push(`/users?term=${value}`), [router]);
    const debounceSearch = useMemo(() => debounce(handleSearch, 700), [handleSearch]);
    useEffect(() => () => (debounceSearch as any)?.cancel?.(), [debounceSearch]);
    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const v = e.target.value;
        setSearchTerm(v);
        debounceSearch(v);
    };


    return (
        <div className="">
            <div className='grid md:grid-cols-3 py-2'>
                <Input
                    onChange={handleChange}
                    type='text' placeholder='Search Users ...'/>
            </div>
            <div className="max-h-[72vh] overflow-y-auto custom-scrollbar ">
                <table className="w-full text-sm text-left rtl:text-right text-color">
                    <thead className="table-header sticky top-0 z-10">
                    <tr>
                        <th className="px-6 py-3 text-center">User Name</th>
                        <th className="px-6 py-3 text-center">User Email</th>
                        <th className="px-6 py-3 text-center">User Role</th>
                        <th className="px-6 py-3 text-center">User Address</th>
                        {/* <th className="px-6 py-3 text-center">User Permissions</th> */}
                        <th className="px-6 py-3 text-center">Status</th>
                        <th className="px-6 py-3 text-center">Actions</th>
                    </tr>
                    </thead>
                    <tbody>
                    {data.data.map((user: any, index: any) => (
                        <tr key={index} className={`table-row`}
                        >
                            <td className="px-6 py-2 flex justify-start items-center text-center text-color">
                                <Image height={100} width={100}
                                       src={user.avatar ? process.env.NEXT_PUBLIC_URL + user.avatar : '/image.png'}
                                       alt={user.name}
                                       className="w-8 h-8 rounded object-cover block mr-4 "/>
                                {user.name}
                            </td>
                            <td className="px-6 py-2 text-center">
                                <span className="text-[13px] font-medium text-color">{user.email}</span>
                            </td>
                            <td className="px-6 py-2 text-center">
                                <span className="text-[13px] font-medium text-color">{user.role}</span>
                            </td>
                            <td className="px-6 py-2 text-center">
                                <span className="text-[13px] font-medium text-color">{user.address??'NA'}</span>
                            </td>
                            {/* <td className="px-6 py-2 text-center">
                                    <span className="inline-block p-1 rounded bg-emerald-500/10 text-emerald-500 font-medium text-[12px] leading-none">
                                        {Array.isArray(user.permissions) ?
                                            user.permissions.map((permission: string) => (permission + ', ')) :
                                            (user.permissions != null ? JSON.parse(user.permissions).map((permission: string) => permission).join(', ') : "No Permissions")
                                        }
                                    </span>
                                </td> */}
                            <td className="px-6 py-2 text-center">
                                {user.status === 'active' ? (
                                    <span
                                        className="inline-block p-1 rounded bg-emerald-500/10 text-emerald-500 font-medium text-[12px] leading-none">
                                        Active
                                    </span>
                                ) : (
                                    <span
                                        className="inline-block p-1 rounded bg-red-500/10 text-red-500 font-medium text-[12px] leading-none">
                                        Inactive
                                    </span>
                                )}
                            </td>
                            <td className="px-6 py-2 text-center flex justify-center items-center space-x-1">
                                <Link href={`/edit-user/${user.id}`} className='primary-btn px-4 py-2 rounded'
                                ><FaRegEdit/>
                                </Link>
                                <DeleteConfirmation id={user.id} Delete={Delete}/>
                            </td>
                        </tr>
                    ))}
                    </tbody>
                </table>
            </div>
            <TablePagination links={data.links} pageNumber={pageNumber} multipleParams={true}
                             url={`/users?term=${searchTerm}`}/>
        </div>
    )
}

export default UsersTable;