import React, { useState } from 'react'
import { Button, Card, Spinner } from 'flowbite-react'
import { formatDistanceToNow } from 'date-fns'
import { FiCheck, FiEye, FiTrash2 } from 'react-icons/fi'

import buttonTheme from '@/lib/themes/button'
import { useNotifications } from '@/lib/context/NotificationContext'
import { Notification, NotificationType } from '@/lib/types/notification'
import ConfirmDeleteNotificationModal from './ConfirmDeleteNotificationModal'

interface NotificationItemProps {
  notification: Notification
  isMarkingAsRead?: boolean
  isDeleting?: boolean
  onMarkAsRead: (id: number) => Promise<void>
  onDeleteNotification: (id: number) => Promise<void>
}

function getNotificationColor(type: NotificationType) {
  switch (type) {
    case 'refund-request':
      return 'border-blue-200 bg-blue-50'
    case 'approved-refund':
      return 'border-green-200 bg-green-50'
    case 'rejected-refund':
      return 'border-red-200 bg-red-50'
    case 'reschedule-request':
      return 'border-blue-200 bg-blue-50'
    case 'approved-reschedule':
      return 'border-green-200 bg-green-50'
    case 'rejected-reschedule':
      return 'border-red-200 bg-red-50'
    case 'order-paid':
      return 'border-green-200 bg-green-50'
    case 'new-order':
      return 'border-amber-200 bg-amber-50'
    case 'failed-payment':
      return 'border-red-200 bg-red-50'
    case 'fastboat-order-confirmation':
    case 'activity-order-confirmation':
    case 'tour-package-order-confirmation':
      return 'border-green-200 bg-green-50'
    case 'withdrawal-request':
      return 'border-yellow-200 bg-yellow-50'
    case 'withdrawal-cancelled':
      return 'border-gray-200 bg-gray-50'
    default:
      return 'border-gray-200 bg-gray-50'
  }
}

export default function NotificationItem({
  notification,
  onMarkAsRead,
  onDeleteNotification,
}: NotificationItemProps) {
  const { deletedNotificationId, goToActionDetail, setDeletedNotificationId } =
    useNotifications()
  const [isDeleting, setIsDeleting] = useState(false)
  const [isMarkingAsRead, setIsMarkingAsRead] = useState(false)
  const [showDeleteModal, setShowDeleteModal] = useState(false)
  const isUnread = !notification.is_read
  const timeAgo = formatDistanceToNow(new Date(notification.created_at), {
    addSuffix: true,
  })

  async function handleDeleteConfirm() {
    setDeletedNotificationId(notification.id)
    setIsDeleting(true)

    await onDeleteNotification(notification.id)

    setDeletedNotificationId(null)
    setIsDeleting(false)
  }

  async function handleMarkAsRead() {
    setDeletedNotificationId(notification.id)
    setIsMarkingAsRead(true)

    await onMarkAsRead(notification.id)

    setDeletedNotificationId(null)
    setIsMarkingAsRead(false)
  }

  return (
    <Card
      className={`sm:p-2 border transition-all shadow-none ${
        isUnread
          ? `${getNotificationColor(notification.type)} border-l-4`
          : 'border-slate-200 bg-white'
      }`}
    >
      <div className="flex items-start gap-4">
        <div className="flex-1 min-w-0">
          <div className="flex items-start justify-between">
            <div className="flex-1">
              <div className="flex items-center gap-2 mb-1">
                <h4 className="text-sm font-medium text-gray-900 hover:underline">
                  {notification.formatted_type}
                </h4>
                {isUnread && (
                  <span className="w-2 h-2 bg-blue-500 rounded-full"></span>
                )}
              </div>

              <p className="text-sm text-gray-700 mb-2 line-clamp-2">
                {notification.message}
              </p>

              <div className="flex items-center gap-4 text-xs text-gray-500">
                <span>{timeAgo}</span>
              </div>
            </div>
          </div>

          <div className="flex items-center gap-2 mt-6">
            {isUnread && (
              <Button
                color="alternative"
                className="text-green-500 hover:text-green-700 focus:ring-0 flex items-center"
                size="xs"
                theme={buttonTheme.button}
                onClick={handleMarkAsRead}
                disabled={isMarkingAsRead || isDeleting}
              >
                {isMarkingAsRead && notification.id === notification.id ? (
                  <>
                    <Spinner size="sm" className="mr-2" />
                    Marking as Read
                  </>
                ) : (
                  <>
                    <FiCheck className="w-3 h-3 mr-2" />
                    Mark as Read
                  </>
                )}
              </Button>
            )}

            <Button
              color="alternative"
              size="xs"
              disabled={isMarkingAsRead || isDeleting}
              className="text-blue-500 hover:text-blue-700 focus:ring-0 flex items-center"
              onClick={() => {
                goToActionDetail(notification)
              }}
            >
              <FiEye className="w-3 h-3" />
              <span className="hidden sm:block ml-2">View</span>
            </Button>

            <Button
              color="alternative"
              className="text-red-500 hover:text-red-700 focus:ring-0 flex items-center"
              size="xs"
              theme={buttonTheme.button}
              disabled={isMarkingAsRead || isDeleting}
              onClick={() => setShowDeleteModal(true)}
            >
              {isDeleting && deletedNotificationId === notification.id ? (
                <>
                  <Spinner size="sm" />
                  <span className="hidden sm:block ml-2">Deleting</span>
                </>
              ) : (
                <>
                  <FiTrash2 className="w-3 h-3" />
                  <span className="hidden sm:block ml-2">Delete</span>
                </>
              )}
            </Button>
          </div>
        </div>
      </div>

      <ConfirmDeleteNotificationModal
        isOpen={showDeleteModal}
        isDeleting={isDeleting}
        onClose={() => setShowDeleteModal(false)}
        onConfirm={handleDeleteConfirm}
        notificationMessage={notification.message}
      />
    </Card>
  )
}
