'use client';

import React, { useEffect, useState } from 'react';
import type { ChatMessage } from './useChat';

interface Props {
  notification: ChatMessage;
  offset:       number;           // px offset from bubble (for stacking)
  onClick:      () => void;       // clicked → open chat
  onDismiss:    () => void;       // remove from queue
}

function Avatar({ name, size = 38 }: { name: string; size?: number }) {
  const safe     = name || 'U';
  const initials = safe.split(' ').map(n => n[0]).join('').slice(0, 2).toUpperCase();
  const palette  = ['#0f766e','#1d4ed8','#7c3aed','#db2777','#ea580c','#0284c7','#059669'];
  const color    = palette[(safe.charCodeAt(0) || 0) % palette.length];
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%', flexShrink: 0,
      background: `linear-gradient(135deg, ${color}cc, ${color})`,
      color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontSize: size * 0.36, fontWeight: 700, fontFamily: 'system-ui, sans-serif',
    }}>{initials}</div>
  );
}

export default function ChatNotification({ notification, offset, onClick, onDismiss }: Props) {
  const [leaving, setLeaving] = useState(false);
  const DURATION = 6000; // auto-dismiss after 6s

  useEffect(() => {
    const t = setTimeout(() => {
      setLeaving(true);
      setTimeout(onDismiss, 260);
    }, DURATION);
    return () => clearTimeout(t);
  }, [onDismiss]);

  const handleClose = (e: React.MouseEvent) => {
    e.stopPropagation();
    setLeaving(true);
    setTimeout(onDismiss, 260);
  };

  const handleClick = () => {
    setLeaving(true);
    setTimeout(() => { onClick(); onDismiss(); }, 150);
  };

  const name = notification.sender_name || 'Someone';
  const time = (() => {
    try { return new Date(notification.created_at).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' }); }
    catch { return ''; }
  })();

  return (
    <>
      <style>{`
        @keyframes notifIn  { from { opacity:0; transform:translateX(120%) scale(0.9); } to { opacity:1; transform:translateX(0) scale(1); } }
        @keyframes notifOut { from { opacity:1; transform:translateX(0) scale(1); }     to { opacity:0; transform:translateX(120%) scale(0.9); } }
        @keyframes notifProgress { from { width:100%; } to { width:0%; } }
        .chat-notif-card:hover { transform: translateY(-2px) !important; box-shadow: 0 16px 48px rgba(0,0,0,0.22), 0 6px 16px rgba(0,0,0,0.1) !important; }
      `}</style>
      <div
        className="chat-notif-card"
        onClick={handleClick}
        style={{
          position: 'fixed',
          bottom: 100 + offset,
          right: 24,
          width: 330,
          backgroundColor: '#fff',
          borderRadius: 14,
          boxShadow: '0 12px 40px rgba(0,0,0,0.18), 0 4px 12px rgba(0,0,0,0.08)',
          border: '1px solid rgba(0,0,0,0.06)',
          zIndex: 10001,
          cursor: 'pointer',
          overflow: 'hidden',
          animation: leaving
            ? 'notifOut 0.25s ease forwards'
            : 'notifIn 0.3s cubic-bezier(0.34,1.56,0.64,1) forwards',
          transition: 'bottom 0.28s ease, transform 0.2s ease, box-shadow 0.2s ease',
        }}
      >
        {/* Top brand bar */}
        <div style={{ height: 3, background: 'linear-gradient(90deg, #0f766e, #0e7490)' }} />

        <div style={{ padding: '12px 14px', display: 'flex', gap: 10, alignItems: 'flex-start' }}>
          <Avatar name={name} size={38} />

          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
              gap: 6, marginBottom: 2,
            }}>
              <span style={{
                fontWeight: 700, fontSize: 13, color: '#0f172a',
                overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                letterSpacing: '-0.2px',
              }}>{name}</span>
              <span style={{ fontSize: 10, color: '#94a3b8', flexShrink: 0 }}>{time}</span>
            </div>

            <div style={{
              fontSize: 9.5, color: '#0f766e', fontWeight: 700,
              marginBottom: 4, letterSpacing: 0.4, textTransform: 'uppercase',
              display: 'flex', alignItems: 'center', gap: 4,
            }}>
              🔔 New message
            </div>

            <div style={{
              fontSize: 12.5, color: '#374151', lineHeight: 1.4,
              display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
              overflow: 'hidden', wordBreak: 'break-word',
            }}>{notification.message}</div>
          </div>

          <button
            onClick={handleClose}
            title="Dismiss"
            style={{
              background: 'none', border: 'none', cursor: 'pointer',
              color: '#94a3b8', fontSize: 14, padding: '2px 6px',
              flexShrink: 0, lineHeight: 1,
              borderRadius: 6, transition: 'all 0.15s',
            }}
            onMouseEnter={e => {
              e.currentTarget.style.color = '#0f172a';
              e.currentTarget.style.backgroundColor = '#f1f5f9';
            }}
            onMouseLeave={e => {
              e.currentTarget.style.color = '#94a3b8';
              e.currentTarget.style.backgroundColor = 'transparent';
            }}
          >✕</button>
        </div>

        {/* Countdown progress bar */}
        <div style={{ height: 2, backgroundColor: '#f1f5f9' }}>
          <div style={{
            height: '100%',
            background: 'linear-gradient(90deg, #0f766e, #0e7490)',
            animation: leaving ? 'none' : `notifProgress ${DURATION}ms linear forwards`,
          }} />
        </div>
      </div>
    </>
  );
}