'use client';

import Link from 'next/link';
import { useEffect, useRef, useState } from 'react';

type NotificationItem = {
  id: string;
  title: string;
  description: string;
  time: string;
  href: string;
  icon: string;
  tone: 'message' | 'campaign' | 'warning' | 'security';
  unread: boolean;
};

const notifications: NotificationItem[] = [
  {
    id: 'message-new',
    title: 'New customer message',
    description: 'A new WhatsApp conversation needs a response from the operations team.',
    time: '2 min ago',
    href: '/dashboard/conversations',
    icon: 'chat_bubble',
    tone: 'message',
    unread: true,
  },
  {
    id: 'campaign-complete',
    title: 'Campaign delivery completed',
    description: 'Flash Sale broadcast finished with 98.4% delivered messages.',
    time: '18 min ago',
    href: '/dashboard/campaigns',
    icon: 'campaign',
    tone: 'campaign',
    unread: true,
  },
  {
    id: 'webhook-warning',
    title: 'Webhook retry detected',
    description: 'One callback endpoint returned a temporary failure and was queued for retry.',
    time: '41 min ago',
    href: '/dashboard/settings/webhook-logs',
    icon: 'webhook',
    tone: 'warning',
    unread: true,
  },
  {
    id: 'security-login',
    title: 'Admin login recorded',
    description: 'System Admin signed in from localhost. Review details in Audit Trail.',
    time: 'Today',
    href: '/dashboard/settings/audit-trail',
    icon: 'shield',
    tone: 'security',
    unread: false,
  },
];

function BellIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true">
      <path
        d="M9.5 18a2.5 2.5 0 0 0 5 0M6 17h12l-1.4-1.6a2 2 0 0 1-.5-1.3V10a4.1 4.1 0 0 0-8.2 0v4.1a2 2 0 0 1-.5 1.3L6 17Z"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

export function NotificationCenter() {
  const [isOpen, setIsOpen] = useState(false);
  const panelRef = useRef<HTMLDivElement | null>(null);
  const unreadCount = notifications.filter((item) => item.unread).length;

  useEffect(() => {
    if (!isOpen) {
      return;
    }

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        setIsOpen(false);
      }
    };

    const onPointerDown = (event: PointerEvent) => {
      if (panelRef.current && !panelRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

    window.addEventListener('keydown', onKeyDown);
    window.addEventListener('pointerdown', onPointerDown);
    return () => {
      window.removeEventListener('keydown', onKeyDown);
      window.removeEventListener('pointerdown', onPointerDown);
    };
  }, [isOpen]);

  return (
    <div className="notification-center" ref={panelRef}>
      <button
        type="button"
        className="dashboard-icon-button notification-trigger"
        aria-label="Notifications"
        aria-expanded={isOpen}
        onClick={() => setIsOpen((value) => !value)}
      >
        <BellIcon />
        {unreadCount > 0 ? <span className="notification-badge">{unreadCount}</span> : null}
      </button>

      {isOpen ? (
        <section className="notification-panel" aria-label="Notification center">
          <div className="notification-panel-head">
            <div>
              <strong>Notifications</strong>
              <p>{unreadCount} unread updates</p>
            </div>
            <Link href="/dashboard/settings/audit-trail" onClick={() => setIsOpen(false)}>
              View audit
            </Link>
          </div>

          <div className="notification-list">
            {notifications.map((item) => (
              <Link
                key={item.id}
                href={item.href}
                className={item.unread ? 'notification-item is-unread' : 'notification-item'}
                onClick={() => setIsOpen(false)}
              >
                <span className={`notification-icon ${item.tone} material-symbols-outlined`}>{item.icon}</span>
                <span className="notification-copy">
                  <strong>{item.title}</strong>
                  <small>{item.description}</small>
                  <em>{item.time}</em>
                </span>
              </Link>
            ))}
          </div>
        </section>
      ) : null}
    </div>
  );
}
