'use client';

import { useEffect } from 'react';
import { useInquiryNotifications } from '@/components/hooks/useInquiryNotifications';
import { usePushNotifications } from '@/components/hooks/usePushNotifications';
import { useNotifications } from './hooks/useNotifications';

// ============================================================================
// NotificationProvider
// ----------------------------------------------------------------------------
// Mounts all three notification channels globally:
//   1. useInquiryNotifications — inquiry SSE stream (unchanged)
//   2. usePushNotifications    — browser push / service worker (unchanged)
//   3. useNotifications        — the generic socket.io channel that carries
//                                audit-request + audit-schedule notifications
//
// ✅ FIXED — previously this component called the hooks and did `return null`,
// so audit notifications arrived in the `toasts` array but were NEVER DRAWN on
// screen. Now it renders that `toasts` array as white in-app cards (bottom
// right), with a colour accent + close button. Nothing else removed.
// ============================================================================

// ── Per-type styling (icon + accent colour) ────────────────────────────────
const TOAST_STYLE: Record<
  string,
  { icon: string; accent: string; bg: string; label: string }
> = {
  AUDIT_REQUEST_SUBMITTED: {
    icon: '📋', accent: '#2563eb', bg: '#eff6ff', label: 'Audit Request Submitted',
  },
  AUDIT_REQUEST_SCHEDULED: {
    icon: '✅', accent: '#059669', bg: '#f0fdf4', label: 'Audit Scheduled',
  },
  AUDIT_REQUEST_REJECTED: {
    icon: '❌', accent: '#dc2626', bg: '#fef2f2', label: 'Audit Request Rejected',
  },
  AUDIT_SCHEDULE_PUBLISHED: {
    icon: '📅', accent: '#1e40af', bg: '#eff6ff', label: 'Audit Schedule Published',
  },
  AUDIT_ROW_CANCELLED: {
    icon: '🚫', accent: '#dc2626', bg: '#fef2f2', label: 'Audit Cancelled',
  },
  AUDIT_ROW_RESCHEDULED: {
    icon: '🔄', accent: '#b45309', bg: '#fffbeb', label: 'Audit Rescheduled',
  },
  AUDIT_SCHEDULE_BULK_CANCELLED: {
    icon: '🚫', accent: '#dc2626', bg: '#fef2f2', label: 'Audits Cancelled',
  },
};

// Fallback styling for any type not listed above.
const DEFAULT_STYLE = {
  icon: '🔔',
  accent: '#6b7280',
  bg: '#f3f4f6',
  label: 'Notification',
};

export default function NotificationProvider() {
  useEffect(() => {
    console.log('✅ NotificationProvider mounted');
  }, []);

  // Channel 1 + 2 — unchanged, kept exactly as before.
  useInquiryNotifications();
  usePushNotifications();

  // Channel 3 — the socket.io channel. We now also READ its `toasts` array
  // and `dismissToast` so we can actually render the cards on screen.
  const { toasts, dismissToast } = useNotifications();

  return (
    <div
      aria-live="polite"
      style={{
        position: 'fixed',
        bottom: 16,
        right: 16,
        zIndex: 99999,
        display: 'flex',
        flexDirection: 'column',
        gap: 10,
        pointerEvents: 'none', // wrapper ignores clicks; cards re-enable below
      }}
    >
      {toasts.map((toast) => {
        const cfg = TOAST_STYLE[toast.type] ?? DEFAULT_STYLE;
        return (
          <div
            key={toast.toastId}
            style={{
              pointerEvents: 'auto', // the card itself IS clickable
              width: 340,
              background: '#fff',
              borderRadius: 12,
              boxShadow:
                '0 8px 32px rgba(0,0,0,0.14), 0 2px 8px rgba(0,0,0,0.08)',
              overflow: 'hidden',
              fontFamily: 'system-ui, -apple-system, sans-serif',
              animation: 'qrs-toast-in 0.25s ease-out',
            }}
          >
            {/* Colour accent bar */}
            <div style={{ height: 3, background: cfg.accent }} />

            <div style={{ padding: '13px 15px 12px' }}>
              {/* Header row */}
              <div
                style={{
                  display: 'flex',
                  alignItems: 'flex-start',
                  justifyContent: 'space-between',
                  gap: 8,
                  marginBottom: 6,
                }}
              >
                <div
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: 8,
                    minWidth: 0,
                  }}
                >
                  <div
                    style={{
                      width: 30,
                      height: 30,
                      borderRadius: 8,
                      background: cfg.bg,
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      fontSize: 15,
                      flexShrink: 0,
                    }}
                  >
                    {cfg.icon}
                  </div>
                  <span
                    style={{
                      fontSize: 10,
                      fontWeight: 700,
                      textTransform: 'uppercase',
                      letterSpacing: '0.05em',
                      color: cfg.accent,
                    }}
                  >
                    {cfg.label}
                  </span>
                </div>
                <button
                  onClick={() => dismissToast(toast.toastId)}
                  aria-label="Dismiss"
                  style={{
                    background: 'none',
                    border: 'none',
                    cursor: 'pointer',
                    color: '#9ca3af',
                    fontSize: 16,
                    lineHeight: 1,
                    padding: '2px 4px',
                    flexShrink: 0,
                  }}
                >
                  ×
                </button>
              </div>

              {/* Title */}
              <div
                style={{
                  fontSize: 13,
                  fontWeight: 700,
                  color: '#111827',
                  marginBottom: 2,
                }}
              >
                {toast.title}
              </div>

              {/* Body */}
              <div
                style={{
                  fontSize: 12,
                  color: '#6b7280',
                  lineHeight: 1.45,
                }}
              >
                {toast.body}
              </div>
            </div>
          </div>
        );
      })}

      {/* Slide-in keyframes */}
      <style>{`
        @keyframes qrs-toast-in {
          from { opacity: 0; transform: translateX(20px); }
          to   { opacity: 1; transform: translateX(0); }
        }
      `}</style>
    </div>
  );
}