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 { useGetProducts, useDeleteProduct } from './hooks/useProductData'
import { useProductFilters } from './hooks/useProductFilters'
import { getProductTableColumns } from './components/ProductTableColumns'
import { useProductFiltersFields } from './components/ProductFiltersFields'
import { Link } from 'react-router-dom'
import { Pages } from '@/config/Pages'

const ProductsList: FC = () => {
    const {
        filters,
        currentPage,
        apiParams,
        handleFiltersChange,
        handlePageChange,
    } = useProductFilters()

    const { data: productsData, isLoading } = useGetProducts(apiParams, filters)
    const { mutate: deleteProduct, isPending: isDeleting } = useDeleteProduct()



    const products = productsData?.data || []
    const columns = getProductTableColumns({
        onDelete: (id: string) => deleteProduct(id),
        isDeleting
    })
    const filterFields = useProductFiltersFields()

    const totalPages = productsData?.meta?.totalPages || 1

    return (
        <div className='mt-5'>
            <div className='flex justify-between items-center'>
                <h1 className='text-lg font-light'>لیست کالاها</h1>
                <Link
                    to={Pages.products.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={products}
                isloading={isLoading}
                pagination={{
                    currentPage,
                    totalPages,
                    onPageChange: handlePageChange,
                }}
            />
        </div>
    )
}

export default ProductsList
