import { useEffect } from 'react'
import { Card } from './ui'
import type { Notification } from '@/lib/notificationService'
import { NotificationItem } from './NotificationItem'
import { NotificationPanelHeader } from './NotificationPanelHeader'
import { t } from '@/lib/i18n'

interface NotificationPanelProps {
  notifications: Notification[]
  unreadCount: number
  onNotificationClick: (notification: Notification) => void
  onDelete: (id: string) => void
  onMarkAllAsRead: () => void
  onClose: () => void
}

function NotificationList({ notifications, onNotificationClick, onDelete }: {
  notifications: Notification[]
  onNotificationClick: (notification: Notification) => void
  onDelete: (id: string) => void
}): React.ReactElement {
  if (notifications.length === 0) {
    return (
      <div className="p-8 text-center text-gray-500">
        <p>{t('notification.empty')}</p>
      </div>
    )
  }

  return (
    <div className="divide-y divide-gray-100">
      {notifications.map((notification) => (
        <NotificationItem
          key={notification.id}
          notification={notification}
          onNotificationClick={onNotificationClick}
          onDelete={onDelete}
        />
      ))}
    </div>
  )
}

export function NotificationPanel({
  notifications,
  unreadCount,
  onNotificationClick,
  onDelete,
  onMarkAllAsRead,
  onClose,
}: NotificationPanelProps): React.ReactElement {
  useEffect(() => {
    const handleEscape = (e: KeyboardEvent): void => {
      if (e.key === 'Escape') {
        onClose()
      }
    }

    document.addEventListener('keydown', handleEscape)
    return () => {
      document.removeEventListener('keydown', handleEscape)
    }
  }, [onClose])

  return (
    <>
      <div className="fixed inset-0 z-40 bg-black bg-opacity-50" onClick={onClose} />
      <Card variant="default" className="absolute right-0 mt-2 w-96 bg-white shadow-xl border-gray-200 z-50 max-h-[600px] flex flex-col">
        <NotificationPanelHeader
          unreadCount={unreadCount}
          onMarkAllAsRead={onMarkAllAsRead}
          onClose={onClose}
        />
        <div className="overflow-y-auto flex-1">
          <NotificationList
            notifications={notifications}
            onNotificationClick={onNotificationClick}
            onDelete={onDelete}
          />
        </div>
      </Card>
    </>
  )
}
