'use client';

import React, { useState, useEffect } from 'react';
import { useChat, ChatRoom, ChatMessage } from './useChat';
import { theme, fontFamily } from './theme';
import { smartTime, avatarColor, initials } from './chatHelpers';
import ChatPanel from './ChatPanel';
import ChatWindow from './ChatWindow';
import NewChatModal from './NewChatModal';
import './chat-responsive.css';

type View = 'closed' | 'panel' | 'window';
type Size = 'normal' | 'expanded';

// ═══════════════════════════════════════════════════════════════════════════
// Notification toast (refined)
// ═══════════════════════════════════════════════════════════════════════════
function NotifAvatar({ name, size = 40 }: { name: string; size?: number }) {
  const color = avatarColor(name);
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%', flexShrink: 0,
      background: `linear-gradient(135deg, ${color}ee 0%, ${color} 100%)`,
      color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontSize: size * 0.38, fontWeight: 600, fontFamily,
    }}>{initials(name)}</div>
  );
}

interface NotifProps {
  notification: ChatMessage;
  offset:       number;
  onClick:      () => void;
  onDismiss:    () => void;
}

function NotificationToast({ notification, offset, onClick, onDismiss }: NotifProps) {
  const [leaving, setLeaving] = useState(false);
  const DURATION = 6000;

  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 previewText =
    notification.type === 'image' ? '📷 Sent a photo' :
    notification.type === 'file'  ? `📎 ${notification.file_name || 'Sent a file'}` :
    notification.message;

  return (
    <div
      onClick={handleClick}
      className="qrs-notif-toast"
      style={{
        position: 'fixed',
        bottom: 100 + offset,
        right: 24,
        width: 360,
        backgroundColor: '#fff',
        borderRadius: theme.radius.lg,
        boxShadow: theme.shadow.xl,
        border: `1px solid ${theme.gray[200]}`,
        zIndex: 10001,
        cursor: 'pointer',
        overflow: 'hidden',
        animation: leaving ? 'notifOut 0.25s ease forwards' : 'notifIn 0.32s cubic-bezier(0.34,1.56,0.64,1) forwards',
        transition: 'bottom 0.3s ease',
        fontFamily,
      }}
    >
      <div style={{ padding: '14px 16px', display: 'flex', gap: 12, alignItems: 'flex-start' }}>
        <NotifAvatar name={name} size={42} />

        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8, marginBottom: 4 }}>
            <span style={{
              fontWeight: 600, fontSize: 13.5, color: theme.gray[900],
              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
              letterSpacing: '-0.01em',
            }}>{name}</span>
            <span style={{ fontSize: 11, color: theme.gray[400], flexShrink: 0, fontWeight: 500 }}>
              {smartTime(notification.created_at)}
            </span>
          </div>
          <div style={{
            fontSize: 13, color: theme.gray[600], lineHeight: 1.45,
            display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
            overflow: 'hidden', wordBreak: 'break-word',
          }}>{previewText}</div>
        </div>

        <button
          onClick={handleClose}
          aria-label="Dismiss"
          style={{
            background: 'none', border: 'none', cursor: 'pointer',
            color: theme.gray[400], fontSize: 16, padding: '4px 8px',
            flexShrink: 0, lineHeight: 1, borderRadius: theme.radius.sm,
            transition: 'all 0.15s',
          }}
          onMouseEnter={e => { e.currentTarget.style.color = theme.gray[700]; e.currentTarget.style.backgroundColor = theme.gray[100]; }}
          onMouseLeave={e => { e.currentTarget.style.color = theme.gray[400]; e.currentTarget.style.backgroundColor = 'transparent'; }}
        >×</button>
      </div>

      <div style={{ height: 2, backgroundColor: theme.gray[100] }}>
        <div style={{
          height: '100%',
          background: theme.gradient.brand,
          animation: leaving ? 'none' : `notifProgress ${DURATION}ms linear forwards`,
        }} />
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// MAIN
// ═══════════════════════════════════════════════════════════════════════════
export default function ChatBubble() {
  const {
    connected, rooms, messages, typing, online,
    totalUnread, getUserId,
    joinRoom, sendMessage, sendFileMessage, sendTyping, markRead,
    createDirectRoom, fetchRooms,
    notifications = [], dismissNotification = (_id: number) => {},
  } = useChat();

  const [view,        setView]        = useState<View>('closed');
  const [size,        setSize]        = useState<Size>('normal');
  const [activeRoom,  setActiveRoom]  = useState<ChatRoom | null>(null);
  const [showNewChat, setShowNewChat] = useState(false);
  const [userId,      setUserId]      = useState<number | null>(null);
  const [pulse,       setPulse]       = useState(false);

  useEffect(() => { setUserId(getUserId()); }, [getUserId]);

  // ESC key closes chat
  useEffect(() => {
    if (view === 'closed') return;
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && size === 'expanded') setSize('normal');
      else if (e.key === 'Escape') setView('closed');
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [view, size]);

  useEffect(() => {
    if (totalUnread > 0 && view === 'closed') {
      setPulse(true);
      const t = setTimeout(() => setPulse(false), 600);
      return () => clearTimeout(t);
    }
  }, [totalUnread, view]);

  const handleSelectRoom = (room: ChatRoom) => {
    setActiveRoom(room);
    setView('window');
    joinRoom(room.id);
  };

  const handleBack = () => {
    setActiveRoom(null);
    setView('panel');
    fetchRooms();
  };

  const handleToggle = () => {
    if (view === 'closed') { setView('panel'); fetchRooms(); }
    else { setView('closed'); setActiveRoom(null); setSize('normal'); }
  };

  const handleNewChat = async (targetUserId: number) => {
    setShowNewChat(false);
    const room = await createDirectRoom(targetUserId);
    if (room) handleSelectRoom(room);
  };

  const handleNotificationClick = (notif: ChatMessage) => {
    const room = rooms.find(r => r.id === notif.room_id);
    if (room) handleSelectRoom(room);
    else { setView('panel'); fetchRooms(); }
  };

  const visibleNotifications = (notifications ?? []).filter(n =>
    !(view === 'window' && activeRoom?.id === n.room_id)
  );

  const isOnline = (uid: number) => online.has(uid);
  if (!userId) return null;

  // Window dimensions
  const isExpanded = size === 'expanded';
  const winWidth   = isExpanded ? 'min(900px, calc(100vw - 48px))' : 420;
  const winHeight  = isExpanded ? 'min(800px, calc(100vh - 120px))' : 640;

  return (
    <>
      <style>{`
        @keyframes chatUp {
          from { opacity:0; transform:translateY(20px) scale(0.95); }
          to   { opacity:1; transform:translateY(0) scale(1); }
        }
        @keyframes pulseBubble {
          0%,100% { box-shadow: 0 4px 24px rgba(99,102,241,0.45); }
          50%      { box-shadow: 0 4px 50px rgba(99,102,241,0.75), 0 0 0 10px rgba(99,102,241,0.12); }
        }
        @keyframes bellShake {
          0%,100% { transform: rotate(0deg); }
          20%     { transform: rotate(-15deg); }
          40%     { transform: rotate(12deg); }
          60%     { transform: rotate(-8deg); }
          80%     { transform: rotate(4deg); }
        }
        @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%; } }
        .qrs-chat-bubble:hover { transform: scale(1.05) !important; }
      `}</style>

      {showNewChat && (
        <NewChatModal onSelect={handleNewChat} onClose={() => setShowNewChat(false)} isOnline={isOnline} />
      )}

      {visibleNotifications.map((notif, i) => (
        <NotificationToast
          key={notif.id}
          notification={notif}
          offset={(visibleNotifications.length - 1 - i) * 96}
          onClick={() => handleNotificationClick(notif)}
          onDismiss={() => dismissNotification(notif.id)}
        />
      ))}

      {view !== 'closed' && (
        <div
          className={`qrs-chat-container ${isExpanded ? 'qrs-expanded' : ''}`}
          style={{
          position: 'fixed',
          bottom: 96,
          right: 24,
          width: winWidth,
          height: winHeight,
          zIndex: 9999,
          borderRadius: theme.radius.xl,
          overflow: 'hidden',
          boxShadow: theme.shadow.xl,
          display: 'flex',
          flexDirection: 'column',
          backgroundColor: '#fff',
          animation: 'chatUp 0.3s cubic-bezier(0.34,1.56,0.64,1)',
          border: `1px solid ${theme.gray[200]}`,
          fontFamily,
          transition: 'width 0.25s ease, height 0.25s ease',
        }}>
          {view === 'panel' && (
            <ChatPanel
              rooms={rooms}
              currentUserId={userId}
              onSelectRoom={handleSelectRoom}
              onClose={() => setView('closed')}
              isOnline={isOnline}
              onNewChat={() => setShowNewChat(true)}
            />
          )}
          {view === 'window' && activeRoom && (
            <ChatWindow
              room={activeRoom}
              messages={messages[activeRoom.id] ?? []}
              currentUserId={userId}
              typingUsers={(typing[activeRoom.id] ?? []).filter(id => id !== userId)}
              onBack={handleBack}
              onSend={sendMessage}
              onSendFile={sendFileMessage}
              onTyping={sendTyping}
              onMarkRead={markRead}
              isOnline={isOnline}
              isExpanded={isExpanded}
              onToggleExpand={() => setSize(s => s === 'normal' ? 'expanded' : 'normal')}
            />
          )}
        </div>
      )}

      <button
        className="qrs-chat-bubble"
        onClick={handleToggle}
        aria-label={view === 'closed' ? 'Open chat' : 'Close chat'}
        style={{
          position: 'fixed', bottom: 24, right: 24,
          width: 60, height: 60, borderRadius: '50%',
          border: 'none', cursor: 'pointer', zIndex: 10000,
          background: theme.gradient.brand,
          color: '#fff', fontSize: 24,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: pulse
            ? `0 4px 50px ${theme.brand[500]}bf, 0 0 0 10px ${theme.brand[500]}1f`
            : `0 4px 24px ${theme.brand[500]}73`,
          transition: 'transform 0.25s cubic-bezier(0.4,0,0.2,1), box-shadow 0.25s',
          animation: pulse ? 'pulseBubble 0.6s ease' : 'none',
          fontFamily,
        }}
      >
        <span style={{
          transition: 'transform 0.25s cubic-bezier(0.4,0,0.2,1)',
          transform: view !== 'closed' ? 'rotate(90deg) scale(0.9)' : 'rotate(0)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          animation: (view === 'closed' && visibleNotifications.length > 0) ? 'bellShake 0.8s ease' : 'none',
        }}>
          {view !== 'closed' ? (
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          ) : totalUnread > 0 ? (
            <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M12 22a2 2 0 0 0 2-2h-4a2 2 0 0 0 2 2zm6-6V11c0-3.07-1.64-5.64-4.5-6.32V4a1.5 1.5 0 0 0-3 0v.68C7.63 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z"/></svg>
          ) : (
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
          )}
        </span>

        {view === 'closed' && totalUnread > 0 && (
          <span style={{
            position: 'absolute', top: -2, right: -2,
            minWidth: 22, height: 22, borderRadius: 99,
            backgroundColor: theme.danger,
            color: '#fff',
            fontSize: 11, fontWeight: 700,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: '0 6px',
            border: '2.5px solid #fff',
            boxShadow: '0 2px 8px rgba(239,68,68,0.4)',
            fontFamily,
          }}>{totalUnread > 99 ? '99+' : totalUnread}</span>
        )}

        <span style={{
          position: 'absolute', bottom: 4, left: 4,
          width: 11, height: 11, borderRadius: '50%',
          backgroundColor: connected ? theme.success : theme.warning,
          border: '2.5px solid #fff',
          transition: 'background-color 0.3s',
        }} />
      </button>
    </>
  );
}