'use client'

import React, { 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 { useAuth } from '@/lib/context/AuthContext'
import { Notification, NotificationType } from '@/lib/types/notification'
import NotificationList from './partials/NotificationList'
import NotificationHeader from './partials/NotificationHeader'
import { usePathname, useRouter } from 'next/navigation'
import { useNotifications } from '@/lib/context/NotificationContext'

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 { user, userManagedMerchants } = useAuth()
  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 pathname = usePathname()
  const router = useRouter()

  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,
        merchantId,
      })

      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(merchantId)

      // 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,
        merchantId,
      })

      // 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,
        merchantId,
      })

      // 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,
        merchantId,
      })
      .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: 'refund-request',
      label: 'Refund Request',
      show: ['manager', 'general_manager', 'supervisor', 'accounting'].includes(
        user?.role as UserRole,
      ),
    },
    {
      value: 'approved-refund',
      label: 'Approved Refund',
      show: ['manager', 'general_manager', 'supervisor'].includes(
        user?.role as UserRole,
      ),
    },
    {
      value: 'rejected-refund',
      label: 'Rejected Refund',
      show: ['manager', 'general_manager', 'supervisor'].includes(
        user?.role as UserRole,
      ),
    },
    {
      value: 'reschedule-request',
      label: 'Reschedule Request',
      show: ['manager', 'general_manager', 'supervisor'].includes(
        user?.role as UserRole,
      ),
    },
    {
      value: 'approved-reschedule',
      label: 'Approved Reschedule',
      show: user?.role === 'supervisor',
    },
    {
      value: 'rejected-reschedule',
      label: 'Rejected Reschedule',
      show: user?.role === 'supervisor',
    },
    {
      value: 'order-paid',
      label: 'Order Paid',
      show: ['manager', 'general_manager', 'supervisor'].includes(
        user?.role as UserRole,
      ),
    },
    {
      value: 'new-order',
      label: 'New Order',
      show: ['manager', 'general_manager', 'supervisor'].includes(
        user?.role as UserRole,
      ),
    },
    {
      value: 'failed-payment',
      label: 'Failed Payment',
      show: ['manager', 'general_manager', 'supervisor'].includes(
        user?.role as UserRole,
      ),
    },
    {
      value: 'fastboat-order-confirmation',
      label: 'Fastboat Order Confirmation',
      show: ['manager', 'general_manager', 'supervisor'].includes(
        user?.role as UserRole,
      ),
    },
    {
      value: 'activity-order-confirmation',
      label: 'Activity Order Confirmation',
      show: ['manager', 'general_manager', 'supervisor'].includes(
        user?.role as UserRole,
      ),
    },
    {
      value: 'tour-package-order-confirmation',
      label: 'Tour Package Order Confirmation',
      show: ['manager', 'general_manager', 'supervisor'].includes(
        user?.role as UserRole,
      ),
    },
    {
      value: 'withdrawal-request',
      label: 'Withdrawal Request',
      show: ['manager', 'general_manager', 'accounting'].includes(
        user?.role as UserRole,
      ),
    },
    {
      value: 'withdrawal-cancelled',
      label: 'Withdrawal Cancelled',
      show: ['manager', 'general_manager', 'accounting'].includes(
        user?.role as UserRole,
      ),
    },
  ]

  // Authorize User
  useEffect(() => {
    // Merchant Dashboard
    if (pathname.includes('/merchant-dashboard')) {
      if (!userManagedMerchants.includes(merchantId || -1)) {
        router.replace(`/merchant-dashboard/${merchantId}`)
      }
    } else {
      // Admin Dashboard
      if (user?.role === 'super_admin') {
        router.replace('/')
      }
    }
  }, [pathname, user, merchantId, userManagedMerchants, router])

  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>
  )
}
