import { type FC, useState } from 'react'
import Table from '@/components/Table'
import Filters from '@/components/Filters'
import { useGetNotifications } from './hooks/useNotificationData'
import { useNotificationFilters } from './hooks/useNotificationFilters'
import { getNotificationTableColumns } from './components/NotificationTableColumns'
import { useNotificationFiltersFields } from './components/NotificationFiltersFields'
import EditNotificationTypeModal from './components/EditNotificationTypeModal'
import type { Notification } from './types/Types'

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

    const { data: notificationsData, isLoading } = useGetNotifications(apiParams)

    const notifications = notificationsData?.data || []
    const filterFields = useNotificationFiltersFields()

    const [isEditModalOpen, setIsEditModalOpen] = useState(false)
    const [selectedNotification, setSelectedNotification] = useState<Notification | null>(null)

    const handleEdit = (notification: Notification) => {
        setSelectedNotification(notification)
        setIsEditModalOpen(true)
    }

    const handleCloseModal = () => {
        setIsEditModalOpen(false)
        setSelectedNotification(null)
    }

    const columns = getNotificationTableColumns({ onEdit: handleEdit })
    const totalPages = Math.ceil(notifications.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<Notification>
                columns={columns}
                data={notifications as Notification[]}
                isloading={isLoading}
                pagination={{
                    currentPage,
                    totalPages,
                    onPageChange: handlePageChange,
                }}
            />

            <EditNotificationTypeModal
                open={isEditModalOpen}
                close={handleCloseModal}
                notification={selectedNotification}
            />
        </div>
    )
}

export default NotificationsList