import { type FC } from 'react'
import { useTranslation } from 'react-i18next'
import { Add } from 'iconsax-react'
import { Link } from 'react-router-dom'
import Table from '@/components/Table'
import Filters from '@/components/Filters'
import Button from '@/components/Button'
import { Pages } from '@/config/Pages'
import { useGetOrders } from './hooks/useOrderData'
import { useOrderFilters } from './hooks/useOrderFilters'
import { getOrderTableColumns } from './components/OrderTableColumns'
import { useOrderFiltersFields } from './components/OrderFiltersFields'
import type { Order } from './types/Types'
import type { RowDataType } from '@/components/types/TableTypes'

const OrdersList: FC = () => {
    const { t } = useTranslation('global')
    const {
        filters,
        currentPage,
        apiParams,
        handleFiltersChange,
        handlePageChange,
        limit,
    } = useOrderFilters()

    const { data: ordersData, isLoading } = useGetOrders(apiParams)

    const orders = ordersData?.data || []
    const columns = getOrderTableColumns({ t })
    const filterFields = useOrderFiltersFields()

    const totalPages = Math.ceil(orders.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.orders.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<Order & RowDataType>
                columns={columns}
                data={orders as (Order & RowDataType)[]}
                isloading={isLoading}
                pagination={{
                    currentPage,
                    totalPages,
                    onPageChange: handlePageChange,
                }}
            />
        </div>
    )
}

export default OrdersList