import { type FC, useEffect } 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,
    } = useOrderFilters()

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

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

    const totalPages = ordersData?.meta?.totalPages || 1
    const effectivePage = Math.min(currentPage, totalPages)

    useEffect(() => {
        if (currentPage > totalPages) {
            handlePageChange(totalPages)
        }
    }, [currentPage, totalPages, handlePageChange])

    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: effectivePage,
                    totalPages,
                    onPageChange: handlePageChange,
                }}
            />
        </div>
    )
}

export default OrdersList