import { type FC } from 'react'
import { useTranslation } from 'react-i18next'
import Table from '@/components/Table'
import Filters from '@/components/Filters'
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>
            </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