import { type FC } from 'react'
import Table from '@/components/Table'
import Filters from '@/components/Filters'
import { Add } from 'iconsax-react'
import Button from '@/components/Button'
import { useGetRoles, useDeleteRole } from './hooks/useRolesData'
import { useRolesFilters } from './hooks/useRolesFilters'
import { getRoleTableColumns } from './components/RoleTableColumns'
import { useRoleFiltersFields } from './components/RoleFiltersFields'
import { Link } from 'react-router-dom'
import { Pages } from '@/config/Pages'

const RolesList: FC = () => {
    const {
        filters,
        currentPage,
        apiParams,
        handleFiltersChange,
        handlePageChange,
        limit,
    } = useRolesFilters()

    const { data: rolesData, isLoading } = useGetRoles(apiParams)
    const { mutate: deleteRole, isPending: isDeleting } = useDeleteRole()

    const roles = rolesData?.data || []
    const columns = getRoleTableColumns({
        onDelete: (id: string) => deleteRole(id),
        isDeleting
    })
    const filterFields = useRoleFiltersFields()

    const totalPages = Math.ceil(roles.length / limit) || 1

    return (
        <div className='mt-5'>
            <div className='flex justify-between items-center'>
                <h1 className='text-lg font-light'>سطح دسترسی ها</h1>
                <Link to={Pages.roles.add}>
                    <Button className='w-fit px-6'>
                        <div className='flex gap-2 items-center'>
                            <Add color='#fff' size={20} />
                            <span>افزودن نقش</span>
                        </div>
                    </Button>
                </Link>
            </div>

            <div className='mt-8'>
                <Filters
                    fields={filterFields}
                    onChange={handleFiltersChange}
                    initialValues={filters}
                    searchField="search"
                />
            </div>

            <Table
                columns={columns}
                data={roles}
                isloading={isLoading}
                pagination={{
                    currentPage,
                    totalPages,
                    onPageChange: handlePageChange,
                }}
            />
        </div>
    )
}

export default RolesList