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 { useGetSchedules, useDeleteSchedule } from './hooks/useScheduleData'
import { useScheduleFilters } from './hooks/useScheduleFilters'
import { getScheduleTableColumns } from './components/ScheduleTableColumns'
import { useScheduleFiltersFields } from './components/ScheduleFiltersFields'
import { Link } from 'react-router-dom'
import { Pages } from '@/config/Pages'

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

    const { data: schedulesData, isLoading } = useGetSchedules(apiParams)
    const { mutate: deleteSchedule, isPending: isDeleting } = useDeleteSchedule()

    const schedules = schedulesData?.data || []
    const columns = getScheduleTableColumns({
        onDelete: (id: string) => deleteSchedule(id),
        isDeleting
    })
    const filterFields = useScheduleFiltersFields()

    const totalPages = Math.ceil(schedules.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.schedule.create}>
                    <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={schedules}
                isLoading={isLoading}
                pagination={{
                    currentPage,
                    totalPages,
                    onPageChange: handlePageChange,
                }}
            />
        </div>
    )
}

export default ScheduleList