'use client'

import { useEffect, useState } from 'react'
import { toast } from 'react-toastify'
import { AxiosError } from 'axios'

import * as PaginationConstant from '@/lib/constants/pagination'
import * as notificationServices from '@/lib/services/notification-services'
import { getKualaLumpurDate } from '@/lib/utils/date'
import { handleApiError } from '@/lib/utils/error-handler'
import { useNotifications } from '@/lib/context/NotificationContext'
import { Notification, NotificationType } from '@/lib/types/notification'
import NotificationList from './_partials/NotificationList'
import NotificationHeader from './_partials/NotificationHeader'

interface MainContentProps {
  merchantId?: number
}

export default function MainContent({ merchantId }: MainContentProps) {
  const [notifications, setNotifications] = useState<Notification[]>([])
  const [isMarkingAllAsRead, setIsMarkingAllAsRead] = useState(false)
  const {
    unreadCount,
    refreshTrigger,
    refreshNotifications,
    setReadNotificationId,
    setDeletedNotificationId,
  } = useNotifications()
  const [selectedType, setSelectedType] = useState<NotificationType | 'all'>(
    'all',
  )
  const [isLoadingInitial, setIsLoadingInitial] = useState(true)
  const [isLoadingMore, setIsLoadingMore] = useState(false)
  const [hasMore, setHasMore] = useState(true)
  const [currentPage, setCurrentPage] = useState(1)

  const loadMoreNotifications = async () => {
    if (isLoadingMore || !hasMore) return

    try {
      setIsLoadingMore(true)

      const notifications = await notificationServices.getAllNotifications({
        page: currentPage + 1,
        limit: PaginationConstant.MIN_DATA_PER_PAGE,
        type: selectedType,
      })

      setNotifications((prev) => [...prev, ...notifications.data])
      setHasMore(notifications.current_page < notifications.last_page)
      setCurrentPage(notifications.current_page)
    } catch (err) {
      handleApiError(err, 'Failed to load notifications')
    } finally {
      setIsLoadingInitial(false)
      setIsLoadingMore(false)
    }
  }

  async function handleMarkAllAsRead() {
    try {
      setIsMarkingAllAsRead(true)

      await notificationServices.markAllAsRead()

      // Refresh notifications to make sure unread count update on other component.
      refreshNotifications()
    } catch (error) {
      handleApiError(error, 'Failed to mark all as read')
    } finally {
      setIsMarkingAllAsRead(false)
    }
  }

  async function handleMarkAsRead(id: number) {
    try {
      await notificationServices.markAsRead(id)

      // Refresh notifications to make sure unread count update on other component.
      refreshNotifications(refreshTrigger)

      // To update read status in other components.
      setReadNotificationId(id)

      setNotifications((prev) =>
        prev.map((notification) =>
          notification.id === id
            ? {
                ...notification,
                is_read: true,
                read_at: getKualaLumpurDate().toISOString(),
              }
            : notification,
        ),
      )
    } catch (error) {
      handleApiError(error, 'Failed to mark notification as read')
    }
  }

  async function handleDeleteNotification(id: number) {
    try {
      await notificationServices.deleteNotification(id)

      // Refresh notifications to make sure unread count update on other component.
      refreshNotifications(refreshTrigger)

      // Sync deletion in other components.
      setDeletedNotificationId(id)

      setNotifications((prev) =>
        prev.filter((notification) => notification.id !== id),
      )

      toast.success('Notification deleted successfully')
    } catch (error) {
      handleApiError(error, 'Failed to delete notification')
    }
  }

  useEffect(() => {
    setIsLoadingInitial(true)

    notificationServices
      .getAllNotifications({
        page: 1,
        limit: PaginationConstant.MIN_DATA_PER_PAGE,
        type: selectedType,
      })
      .then((data) => {
        setNotifications(data.data)
        setHasMore(data.current_page < data.last_page)
        setCurrentPage(data.current_page)
      })
      .catch((error) => {
        if (error instanceof AxiosError) {
          toast.error(error.response?.data?.message)
        }
      })
      .finally(() => {
        setIsLoadingInitial(false)
      })
  }, [refreshTrigger, selectedType, merchantId])

  // Get all possible types for dropdown
  const notificationTypes: {
    value: NotificationType | 'all'
    label: string
    show: boolean
  }[] = [
    { value: 'all', label: 'All Types', show: true },
    {
      value: 'partner-order-placed',
      label: 'Order Placed',
      show: true,
    },
    {
      value: 'withdrawal-completed',
      label: 'Withdrawal Completed',
      show: true,
    },
    {
      value: 'withdrawal-rejected',
      label: 'Withdrawal Rejected',
      show: true,
    },
    {
      value: 'withdrawal-processed',
      label: 'Withdrawal Processed',
      show: true,
    },
  ]

  return (
    <div className="space-y-6">
      <NotificationHeader
        unreadCount={unreadCount}
        isMarkingAllAsRead={isMarkingAllAsRead}
        selectedType={selectedType}
        onMarkAllAsRead={handleMarkAllAsRead}
        onTypeChange={(newType) => {
          setSelectedType(newType)
          setIsLoadingInitial(true)
          setCurrentPage(1)
          setNotifications([])
        }}
        notificationTypes={notificationTypes}
      />

      <NotificationList
        notifications={notifications}
        hasMore={hasMore}
        isLoadingMore={isLoadingMore}
        isLoadingInitial={isLoadingInitial}
        onLoadMore={loadMoreNotifications}
        onMarkAsRead={handleMarkAsRead}
        onDeleteNotification={handleDeleteNotification}
      />
    </div>
  )
}
