import React, { useState } from 'react';

const friends = [
  { id: 1, name: 'Trevor', tag: 'Trevor#0042', avatar: 'T', gradient: 'linear-gradient(135deg, #ff0000, #cc0000)', status: 'online', activity: 'Working on AeThex' },
  { id: 2, name: 'Sarah', tag: 'Sarah#1337', avatar: 'S', gradient: 'linear-gradient(135deg, #ffa500, #ff8c00)', status: 'online', activity: 'Playing Valorant' },
  { id: 3, name: 'Marcus', tag: 'Marcus#2048', avatar: 'M', gradient: 'linear-gradient(135deg, #0066ff, #003380)', status: 'idle' },
  { id: 4, name: 'DevUser_2847', tag: 'DevUser_2847#2847', avatar: 'D', status: 'dnd', activity: 'Do Not Disturb' },
  { id: 5, name: 'JohnDev', tag: 'JohnDev#9999', avatar: 'J', status: 'offline' },
];

const dmConversations = [
  { id: 1, user: friends[0], lastMessage: 'The auth system is ready!', time: '2m', unread: 2 },
  { id: 2, user: friends[1], lastMessage: 'Check out the new Nexus build', time: '15m', unread: 0 },
  { id: 3, user: friends[2], lastMessage: 'Thanks for the help!', time: '1h', unread: 0 },
  { id: 4, user: { name: 'Group Chat', avatar: '👥', isGroup: true, members: ['Trevor', 'Sarah', 'Marcus'] }, lastMessage: 'Sarah: Let\'s sync up tomorrow', time: '3h', unread: 5 },
];

const pendingRequests = [
  { id: 1, name: 'NewDev123', tag: 'NewDev123#4567', avatar: 'N', type: 'incoming', mutualServers: 2 },
  { id: 2, name: 'CoolCoder', tag: 'CoolCoder#8899', avatar: 'C', type: 'outgoing' },
];

export default function DMsView({ onSelectDM, onOpenProfile }) {
  const [activeTab, setActiveTab] = useState('online');
  const [searchQuery, setSearchQuery] = useState('');

  const tabs = [
    { id: 'online', label: 'Online' },
    { id: 'all', label: 'All' },
    { id: 'pending', label: 'Pending', count: pendingRequests.length },
    { id: 'blocked', label: 'Blocked' },
    { id: 'add', label: 'Add Friend', isAction: true },
  ];

  const statusColors = {
    online: '#3ba55d',
    idle: '#faa61a',
    dnd: '#ed4245',
    offline: '#747f8d',
  };

  const filteredFriends = friends.filter((f) => {
    if (activeTab === 'online') return f.status === 'online';
    if (activeTab === 'all') return true;
    return true;
  }).filter((f) => 
    f.name.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <div className="dms-view">
      {/* DMs Sidebar */}
      <div className="dms-sidebar">
        <div className="dms-search">
          <input 
            type="text" 
            placeholder="Find or start a conversation"
            className="dms-search-input"
          />
        </div>

        <div className="dms-section">
          <div className="dms-section-header">
            <span>Friends</span>
          </div>
          <div 
            className="dms-nav-item"
            onClick={() => setActiveTab('online')}
          >
            <span className="nav-icon">👥</span>
            <span>Friends</span>
          </div>
          <div className="dms-nav-item">
            <span className="nav-icon">🚀</span>
            <span>Nitro</span>
          </div>
          <div className="dms-nav-item">
            <span className="nav-icon">🛒</span>
            <span>Shop</span>
          </div>
        </div>

        <div className="dms-section">
          <div className="dms-section-header">
            <span>Direct Messages</span>
            <button className="add-dm-btn">+</button>
          </div>
          
          {dmConversations.map((dm) => (
            <div 
              key={dm.id}
              className="dm-item"
              onClick={() => onSelectDM?.(dm)}
            >
              <div className="dm-avatar" style={{ background: dm.user.gradient || '#36393f' }}>
                {dm.user.avatar}
                {!dm.user.isGroup && (
                  <div 
                    className="dm-status"
                    style={{ background: statusColors[dm.user.status] || statusColors.offline }}
                  />
                )}
              </div>
              <div className="dm-info">
                <div className="dm-name">
                  {dm.user.name}
                  {dm.user.isGroup && <span className="group-count">{dm.user.members?.length}</span>}
                </div>
                <div className="dm-preview">{dm.lastMessage}</div>
              </div>
              {dm.unread > 0 && (
                <div className="dm-unread">{dm.unread}</div>
              )}
              <button className="dm-close" onClick={(e) => { e.stopPropagation(); }}>✕</button>
            </div>
          ))}
        </div>
      </div>

      {/* Friends List Panel */}
      <div className="friends-panel">
        <div className="friends-header">
          <div className="friends-title">
            <span className="friends-icon">👥</span>
            <span>Friends</span>
          </div>
          <div className="friends-tabs">
            {tabs.map((tab) => (
              <button
                key={tab.id}
                className={`friends-tab ${activeTab === tab.id ? 'active' : ''} ${tab.isAction ? 'action' : ''}`}
                onClick={() => setActiveTab(tab.id)}
              >
                {tab.label}
                {tab.count > 0 && <span className="tab-count">{tab.count}</span>}
              </button>
            ))}
          </div>
        </div>

        {activeTab === 'add' ? (
          <div className="add-friend-panel">
            <h2>Add Friend</h2>
            <p>You can add friends with their AeThex username.</p>
            <div className="add-friend-input">
              <input 
                type="text" 
                placeholder="Enter a Username#0000"
                className="friend-input"
              />
              <button className="send-request-btn">Send Friend Request</button>
            </div>
          </div>
        ) : activeTab === 'pending' ? (
          <div className="pending-requests">
            <div className="friends-search">
              <input 
                type="text" 
                placeholder="Search"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
              />
            </div>
            <div className="friends-count">PENDING — {pendingRequests.length}</div>
            {pendingRequests.map((req) => (
              <div key={req.id} className="friend-item">
                <div className="friend-avatar">{req.avatar}</div>
                <div className="friend-info">
                  <div className="friend-name">{req.name}</div>
                  <div className="friend-tag">
                    {req.type === 'incoming' ? 'Incoming Friend Request' : 'Outgoing Friend Request'}
                  </div>
                </div>
                <div className="friend-actions">
                  {req.type === 'incoming' && (
                    <>
                      <button className="friend-action accept">✓</button>
                      <button className="friend-action decline">✕</button>
                    </>
                  )}
                  {req.type === 'outgoing' && (
                    <button className="friend-action decline">✕</button>
                  )}
                </div>
              </div>
            ))}
          </div>
        ) : (
          <>
            <div className="friends-search">
              <input 
                type="text" 
                placeholder="Search"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
              />
            </div>
            <div className="friends-count">
              {activeTab === 'online' ? 'ONLINE' : 'ALL FRIENDS'} — {filteredFriends.length}
            </div>
            <div className="friends-list">
              {filteredFriends.map((friend) => (
                <div 
                  key={friend.id} 
                  className="friend-item"
                  onClick={() => onOpenProfile?.(friend)}
                >
                  <div className="friend-avatar" style={{ background: friend.gradient || '#36393f' }}>
                    {friend.avatar}
                    <div 
                      className="friend-status"
                      style={{ background: statusColors[friend.status] }}
                    />
                  </div>
                  <div className="friend-info">
                    <div className="friend-name">{friend.name}</div>
                    <div className="friend-activity">{friend.activity || friend.status}</div>
                  </div>
                  <div className="friend-actions">
                    <button className="friend-action" title="Message">💬</button>
                    <button className="friend-action" title="Voice Call">📞</button>
                    <button className="friend-action" title="Video Call">📹</button>
                    <button className="friend-action" title="More">⋯</button>
                  </div>
                </div>
              ))}
            </div>
          </>
        )}
      </div>

      {/* Activity/Now Playing Panel */}
      <div className="activity-panel">
        <h3>Active Now</h3>
        <div className="activity-placeholder">
          <p>It's quiet for now...</p>
          <p className="activity-hint">When a friend starts an activity—like playing a game or hanging out on voice—we'll show it here!</p>
        </div>
      </div>
    </div>
  );
}
