'use client';

import { useEffect, useRef } from 'react';
import { notification } from 'antd';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { useWhatsAppSocket } from './useWhatsAppSocket';
import { getConversations } from '../service';

/** Returns up to 2 uppercase initials from a full name */
const getInitials = (name: string) =>
  name.split(' ').filter(Boolean).slice(0, 2).map((n) => n[0].toUpperCase()).join('');

/** Picks a deterministic colour from the name's first char */
const getAvatarColor = (name: string) => {
  const palette = [
    '#0e8744', '#184b73', '#e67e22', '#8e44ad',
    '#2980b9', '#c0392b', '#27ae60', '#d35400',
  ];
  return palette[name.charCodeAt(0) % palette.length];
};

const WhatsAppMessageNotifier = () => {
  const { data: session } = useSession();
  const router = useRouter();

  // Cache: leadId (string) → lead_name (string)
  const nameMapRef = useRef<Record<string, string>>({});

  // Load conversations once on mount (and whenever the session becomes available)
  useEffect(() => {
    if (!session?.user?.id) return;

    const loadNames = async () => {
      try {
        const res = await getConversations('');
        if (res?.success && Array.isArray(res.data)) {
          const map: Record<string, string> = {};
          res.data.forEach((conv: any) => {
            if (conv.lead_id && conv.lead_name) {
              map[String(conv.lead_id)] = conv.lead_name;
            }
          });
          nameMapRef.current = map;
        }
      } catch {
        // non-critical — silently ignore
      }
    };

    loadNames();
  }, [session?.user?.id]);

  useWhatsAppSocket({
    sessionUserId: session?.user?.id,
    onMessageReceived: async (_convId, leadId, newMsg, _log) => {
      // Only notify for incoming messages (not ones we sent)
      if (newMsg.type !== 'received') return;

      const leadIdStr = String(leadId);
      let senderName = nameMapRef.current[leadIdStr];

      // If name not in cache yet, do a quick refresh then pick it up
      if (!senderName) {
        try {
          const res = await getConversations('');
          if (res?.success && Array.isArray(res.data)) {
            res.data.forEach((conv: any) => {
              if (conv.lead_id && conv.lead_name) {
                nameMapRef.current[String(conv.lead_id)] = conv.lead_name;
              }
            });
          }
        } catch {
          // ignore
        }
        senderName = nameMapRef.current[leadIdStr] || 'WhatsApp Message';
      }

      const previewText = newMsg.text
        ? newMsg.text.replace(/<[^>]*>/g, '').slice(0, 90)
        : 'Sent you a message';

      const initials = getInitials(senderName);
      const avatarBg = getAvatarColor(senderName);
      const now = new Date().toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });

      notification.open({
        key: `wa-msg-${newMsg.id}`,
        icon: null,
        message: null,
        description: (
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: '12px', cursor: 'pointer' }}>
            {/* Avatar */}
            <div
              style={{
                width: 44, height: 44, borderRadius: '50%', background: avatarBg,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                flexShrink: 0, fontSize: 15, fontWeight: 700, color: '#fff',
                letterSpacing: '0.5px', boxShadow: '0 2px 6px rgba(0,0,0,0.18)',
              }}
            >
              {initials}
            </div>
            {/* Content */}
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ marginBottom: 4 }}>
                <span style={{ fontWeight: 700, fontSize: 14, color: '#111', lineHeight: 1.3 }}>
                  {senderName}
                </span>
              </div>
              <p style={{
                margin: 0, fontSize: 13, color: '#555', lineHeight: 1.45,
                overflow: 'hidden', display: '-webkit-box',
                WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
              }}>
                {previewText}
              </p>
              <div style={{ textAlign: 'right', marginTop: 6 }}>
                <span style={{ fontSize: 11, color: '#aaa' }}>{now}</span>
              </div>
            </div>
          </div>
        ),
        placement: 'topRight',
        duration: 6,
        style: {
          padding: '14px 16px', borderRadius: '12px',
          boxShadow: '0 8px 32px rgba(0,0,0,0.14)',
          background: '#fff', border: '1px solid #f0f0f0',
          borderLeft: '4px solid #25d366', cursor: 'pointer',
        },
        onClick: () => {
          notification.destroy(`wa-msg-${newMsg.id}`);
          router.push(`/messages?leadId=${leadId}`);
        },
      });
    },
    // Status updates don't need global notifications
    onStatusUpdated: () => {},
  });

  return null;
};

export default WhatsAppMessageNotifier;
