'use client';

import React, { useEffect, useState, useRef } from 'react';

interface User { id: number; firstName: string; lastName: string; email: string; }
interface Props { onSelect: (userId: number) => void | Promise<void>; onClose: () => void; isOnline: (userId: number) => boolean; }

const API = process.env.NEXT_PUBLIC_API_URL?.replace('/api', '') ?? 'http://localhost:3007';

export default function NewChatModal({ onSelect, onClose, isOnline }: Props) {
  const [users,   setUsers]   = useState<User[]>([]);
  const [search,  setSearch]  = useState('');
  const [loading, setLoading] = useState(true);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    const token = localStorage.getItem('access_token') || '';
    fetch(`${API}/api/chat/users`, { headers: { Authorization: `Bearer ${token}` } })
      .then(r => r.json()).then(d => { setUsers(d); setLoading(false); })
      .catch(() => setLoading(false));
    setTimeout(() => inputRef.current?.focus(), 80);
  }, []);

  const filtered = users.filter(u =>
    `${u.firstName} ${u.lastName} ${u.email}`.toLowerCase().includes(search.toLowerCase())
  );
  const onlineUsers  = filtered.filter(u => isOnline(u.id));
  const offlineUsers = filtered.filter(u => !isOnline(u.id));

  function UserRow({ user }: { user: User }) {
    const name   = `${user.firstName} ${user.lastName}`.trim();
    const online = isOnline(user.id);
    const initials = name.split(' ').map(n => n[0]).join('').slice(0, 2).toUpperCase() || '?';
    const palette  = ['#0f766e','#1d4ed8','#7c3aed','#db2777','#ea580c','#0284c7'];
    const color    = palette[(name.charCodeAt(0) || 0) % palette.length];
    return (
      <div onClick={() => onSelect(user.id)} style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '10px 16px', cursor: 'pointer', transition: 'background 0.1s',
      }}
        onMouseEnter={e => (e.currentTarget.style.backgroundColor = '#f8fafc')}
        onMouseLeave={e => (e.currentTarget.style.backgroundColor = '#fff')}
      >
        <div style={{ position: 'relative' }}>
          <div style={{
            width: 40, height: 40, borderRadius: '50%', flexShrink: 0,
            background: `linear-gradient(135deg, ${color}cc, ${color})`,
            color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 14, fontWeight: 700, fontFamily: 'system-ui, sans-serif',
          }}>{initials}</div>
          <div style={{
            position: 'absolute', bottom: 1, right: 1,
            width: 10, height: 10, borderRadius: '50%',
            backgroundColor: online ? '#22c55e' : '#d1d5db',
            border: '2px solid #fff',
          }} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 13, color: '#0f172a' }}>{name}</div>
          <div style={{ fontSize: 11, color: '#94a3b8', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {user.email}
          </div>
        </div>
        {online && (
          <span style={{
            fontSize: 10, fontWeight: 700, color: '#059669',
            backgroundColor: '#f0fdf4', padding: '2px 8px',
            borderRadius: 99, border: '1px solid #bbf7d0', flexShrink: 0,
          }}>Online</span>
        )}
      </div>
    );
  }

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 10001,
      backgroundColor: 'rgba(0,0,0,0.4)', backdropFilter: 'blur(3px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }} onClick={onClose}>
      <div style={{
        backgroundColor: '#fff', borderRadius: 20, width: 340, maxHeight: 540,
        overflow: 'hidden', display: 'flex', flexDirection: 'column',
        boxShadow: '0 24px 80px rgba(0,0,0,0.25)',
        animation: 'modalIn 0.22s cubic-bezier(0.34,1.56,0.64,1)',
      }} onClick={e => e.stopPropagation()}>
        <style>{`@keyframes modalIn{from{opacity:0;transform:scale(0.9)}to{opacity:1;transform:scale(1)}}`}</style>

        {/* Header */}
        <div style={{
          padding: '16px 18px',
          background: 'linear-gradient(145deg, #0f766e 0%, #0e7490 100%)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        }}>
          <div>
            <div style={{ fontWeight: 800, fontSize: 15, color: '#fff' }}>New Message</div>
            <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.7)', marginTop: 1 }}>
              {users.length} team member{users.length !== 1 ? 's' : ''}
            </div>
          </div>
          <button onClick={onClose} style={{
            background: 'rgba(255,255,255,0.18)', border: 'none', borderRadius: 8,
            color: '#fff', cursor: 'pointer', padding: '7px 10px', fontSize: 14, fontWeight: 700,
          }}>✕</button>
        </div>

        {/* Search */}
        <div style={{ padding: '10px 14px', borderBottom: '1px solid #f1f5f9', backgroundColor: '#fff' }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px',
            borderRadius: 10, border: '1.5px solid #e2e8f0', backgroundColor: '#f8fafc',
            transition: 'border-color 0.15s',
          }}
            onFocusCapture={e => ((e.currentTarget as HTMLDivElement).style.borderColor = '#0f766e')}
            onBlurCapture={e  => ((e.currentTarget as HTMLDivElement).style.borderColor = '#e2e8f0')}
          >
            <span style={{ fontSize: 13, color: '#9ca3af' }}>🔍</span>
            <input ref={inputRef} value={search} onChange={e => setSearch(e.target.value)}
              placeholder="Search by name or email..."
              style={{ flex: 1, border: 'none', outline: 'none', fontSize: 12.5, backgroundColor: 'transparent', fontFamily: 'system-ui, sans-serif', color: '#0f172a' }}
            />
            {search && (
              <button onClick={() => setSearch('')} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#9ca3af', fontSize: 14 }}>✕</button>
            )}
          </div>
        </div>

        {/* Users */}
        <div style={{ flex: 1, overflowY: 'auto' }}>
          {loading ? (
            <div style={{ padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: 12 }}>
              {[1,2,3,4].map(i => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <div style={{ width: 40, height: 40, borderRadius: '50%', backgroundColor: '#f1f5f9' }} />
                  <div style={{ flex: 1 }}>
                    <div style={{ height: 12, backgroundColor: '#f1f5f9', borderRadius: 6, width: `${50 + i * 10}%`, marginBottom: 6 }} />
                    <div style={{ height: 10, backgroundColor: '#f8fafc', borderRadius: 6, width: `${60 + i * 8}%` }} />
                  </div>
                </div>
              ))}
            </div>
          ) : filtered.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '40px 20px', color: '#94a3b8' }}>
              <div style={{ fontSize: 28, marginBottom: 8 }}>🔍</div>
              <div style={{ fontSize: 13, fontWeight: 600, color: '#374151' }}>No users found</div>
            </div>
          ) : (
            <>
              {onlineUsers.length > 0 && (
                <>
                  <div style={{ padding: '8px 16px 4px', fontSize: 10, fontWeight: 700, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: 1 }}>
                    Online — {onlineUsers.length}
                  </div>
                  {onlineUsers.map(u => <UserRow key={u.id} user={u} />)}
                </>
              )}
              {offlineUsers.length > 0 && (
                <>
                  <div style={{ padding: '8px 16px 4px', fontSize: 10, fontWeight: 700, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: 1 }}>
                    Offline — {offlineUsers.length}
                  </div>
                  {offlineUsers.map(u => <UserRow key={u.id} user={u} />)}
                </>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}