// components/hooks/useInquiryNotifications.tsx
'use client';

import { useEffect, useRef } from 'react';
import toast from 'react-hot-toast';
import { playNotificationSound } from '@/lib/notificationSound'; // ✅ ADD

const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:3007/api';

interface SSENotification {
  dbId:          number;
  type:          string;
  inquiry_ref:   string;
  company_name:  string;
  message:       string;
  timestamp:     string;
  pdf_url?:      string;
  docx_url?:     string;
}

interface Options {
  onStatusChange?:    () => void;
  onNewNotification?: () => void;
}

// ── Download with auth ────────────────────────────────────────────────────────
async function downloadFile(url: string, filename: string) {
  const token =
    localStorage.getItem('access_token') ||
    localStorage.getItem('token') || '';
  const res = await fetch(url, {
    headers: { Authorization: `Bearer ${token}` },
    credentials: 'include',
  });
  if (!res.ok) { toast.error('Download failed'); return; }
  const blob  = await res.blob();
  const link  = document.createElement('a');
  link.href   = URL.createObjectURL(blob);
  link.download = filename;
  link.click();
  URL.revokeObjectURL(link.href);
}

// ── Get logged-in userId ──────────────────────────────────────────────────────
function getUserId(): number | null {
  try {
    const raw = localStorage.getItem('user');
    if (raw) {
      const parsed = JSON.parse(raw);
      const id = parsed?.id ?? parsed?.userId ?? parsed?.user_id ?? null;
      if (id) return Number(id);
    }
  } catch { /* ignore */ }
  try {
    const token =
      localStorage.getItem('access_token') ||
      localStorage.getItem('token');
    if (token) {
      const payload = JSON.parse(atob(token.split('.')[1]));
      const id = payload?.id ?? payload?.userId ?? payload?.sub ?? null;
      if (id) return Number(id);
    }
  } catch { /* ignore */ }
  return null;
}

// ── Notification config per type ──────────────────────────────────────────────
const NOTIF_CONFIG: Record<string, {
  icon:       string;
  accent:     string;
  bg:         string;
  labelColor: string;
  label:      string;
  sound:      'default' | 'success' | 'error';
}> = {
  NEW_INQUIRY:       { icon: '📋', accent: '#2563eb', bg: '#eff6ff', labelColor: '#1e40af', label: 'New Inquiry',        sound: 'default' },
  IN_REVIEW:         { icon: '🔍', accent: '#7c3aed', bg: '#f5f3ff', labelColor: '#5b21b6', label: 'In Review',          sound: 'default' },
  DRAFT_READY:       { icon: '📄', accent: '#0f766e', bg: '#f0fdfa', labelColor: '#115e59', label: 'Draft Ready',        sound: 'success' },
  CHANGES_REQUESTED: { icon: '↩',  accent: '#dc2626', bg: '#fef2f2', labelColor: '#991b1b', label: 'Changes Requested',  sound: 'error'   },
  CLIENT_CONFIRMED:  { icon: '✅', accent: '#059669', bg: '#f0fdf4', labelColor: '#065f46', label: 'Client Confirmed',   sound: 'success' },
  FINAL_ISSUED:      { icon: '🏆', accent: '#0f766e', bg: '#f0fdfa', labelColor: '#134e4a', label: 'Final Issued',       sound: 'success' },
};

// ── Modern notification card ──────────────────────────────────────────────────
function NotifCard({
  t: toast_,
  event,
  cfg,
}: {
  t: { id: string };
  event: SSENotification;
  cfg: typeof NOTIF_CONFIG[string];
}) {
  const hasDl = !!(event.pdf_url || event.docx_url);

  return (
    <div style={{
      width: 340,
      backgroundColor: '#fff',
      borderRadius: 12,
      boxShadow: '0 8px 32px rgba(0,0,0,0.12), 0 2px 8px rgba(0,0,0,0.08)',
      overflow: 'hidden',
      fontFamily: 'system-ui, -apple-system, sans-serif',
    }}>
      {/* Colour accent bar */}
      <div style={{ height: 3, backgroundColor: cfg.accent }} />

      <div style={{ padding: '14px 16px 12px' }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{
              width: 32, height: 32, borderRadius: 8,
              backgroundColor: cfg.bg,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 15, flexShrink: 0,
            }}>
              {cfg.icon}
            </div>
            <div>
              <div style={{
                display: 'inline-block',
                padding: '2px 8px', borderRadius: 20,
                fontSize: 10, fontWeight: 700,
                textTransform: 'uppercase', letterSpacing: '0.05em',
                backgroundColor: cfg.bg, color: cfg.labelColor,
                marginBottom: 1,
              }}>
                {cfg.label}
              </div>
              <div style={{ fontSize: 10, color: '#9ca3af', fontFamily: 'monospace' }}>
                {event.inquiry_ref}
              </div>
            </div>
          </div>
          <button
            onClick={() => toast.dismiss(toast_.id)}
            style={{
              background: 'none', border: 'none', cursor: 'pointer',
              color: '#9ca3af', fontSize: 16, lineHeight: 1,
              padding: '2px 4px', borderRadius: 4,
            }}>
            ×
          </button>
        </div>

        {/* Company */}
        <div style={{ fontSize: 11, color: '#6b7280', marginBottom: 4, fontWeight: 500 }}>
          {event.company_name}
        </div>

        {/* Message */}
        <p style={{
          margin: '0 0 12px', fontSize: 13, color: '#111827',
          lineHeight: 1.45, fontWeight: 500,
        }}>
          {event.message.replace(/^\S+\s/, '')}
        </p>

        {/* Download buttons — DRAFT_READY only */}
        {hasDl && (
          <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
            {event.pdf_url && (
              <button
                onClick={() => {
                  downloadFile(`${API_BASE}${event.pdf_url}`, `${event.inquiry_ref}_DRAFT.pdf`);
                  toast.dismiss(toast_.id);
                }}
                style={{
                  flex: 1, padding: '7px 10px', borderRadius: 7, border: 'none',
                  backgroundColor: '#0f766e', color: '#fff',
                  fontSize: 12, fontWeight: 600, cursor: 'pointer',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5,
                }}>
                ⬇ Download PDF
              </button>
            )}
            {event.docx_url && (
              <button
                onClick={() => {
                  downloadFile(`${API_BASE}${event.docx_url}`, `${event.inquiry_ref}_DRAFT.docx`);
                  toast.dismiss(toast_.id);
                }}
                style={{
                  flex: 1, padding: '7px 10px', borderRadius: 7, border: 'none',
                  backgroundColor: '#2563eb', color: '#fff',
                  fontSize: 12, fontWeight: 600, cursor: 'pointer',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5,
                }}>
                ⬇ Download Word
              </button>
            )}
          </div>
        )}

        {/* Footer */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          paddingTop: 8, borderTop: '1px solid #f3f4f6',
        }}>
          <span style={{ fontSize: 10, color: '#9ca3af' }}>
            {new Date(event.timestamp).toLocaleTimeString('en-GB', {
              hour: '2-digit', minute: '2-digit',
            })}
          </span>
          <button
            onClick={() => toast.dismiss(toast_.id)}
            style={{
              background: 'none', border: '1px solid #e5e7eb',
              borderRadius: 6, padding: '3px 10px',
              fontSize: 11, color: '#6b7280', cursor: 'pointer',
            }}>
            Dismiss
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Show notification + play sound ────────────────────────────────────────────
function showNotification(event: SSENotification) {
  const cfg = NOTIF_CONFIG[event.type] ?? {
    icon: '🔔', accent: '#6b7280', bg: '#f3f4f6',
    labelColor: '#374151', label: event.type, sound: 'default' as const,
  };

  // ✅ Play sound based on notification type
  playNotificationSound(cfg.sound);

  toast.custom(
    (t) => <NotifCard t={t} event={event} cfg={cfg} />,
    {
      duration: event.type === 'DRAFT_READY' ? 25000 : 8000,
      position: 'top-right',
    },
  );
}

// ── Main hook ─────────────────────────────────────────────────────────────────
export function useInquiryNotifications({
  onStatusChange,
  onNewNotification,
}: Options = {}) {
  const esRef = useRef<EventSource | null>(null);

  useEffect(() => {
    const userId = getUserId();
    console.log('🔌 SSE Hook — userId:', userId);
    if (!userId) return;

    let es: EventSource;
    let retryTimeout: ReturnType<typeof setTimeout>;

    const connect = () => {
      const url = `${API_BASE}/inquiry-notifications/stream?userId=${userId}`;
      es = new EventSource(url);
      esRef.current = es;

      es.onopen = () => console.log('✅ SSE Connected! userId:', userId);

      es.onmessage = (event) => {
        try {
          const data: SSENotification = JSON.parse(event.data);
          showNotification(data); // ✅ shows card + plays sound
          onStatusChange?.();
          onNewNotification?.();
          if (typeof window !== 'undefined') {
            (window as any).__refreshNotificationBell?.();
          }
        } catch (err) {
          console.error('SSE parse error:', err);
        }
      };

      es.onerror = () => {
        es.close();
        retryTimeout = setTimeout(() => connect(), 5000);
      };
    };

    connect();

    return () => {
      clearTimeout(retryTimeout);
      es?.close();
    };

  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
}