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

export default function MemberWorkload() {
  const [contacts, setContacts] = useState<any[]>([]);
  const [tasks, setTasks] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    setLoading(true);
    try {
      const [contactsResult, tasksResult] = await Promise.all([
        window.mcp.callTool('wrike_list_contacts', {}),
        window.mcp.callTool('wrike_list_tasks', {}),
      ]);
      setContacts(contactsResult.contacts || []);
      setTasks(tasksResult.tasks || []);
    } catch (error) {
      console.error('Failed to load data:', error);
    } finally {
      setLoading(false);
    }
  };

  const getWorkload = (contactId: string) => {
    return tasks.filter(t => t.responsibleIds?.includes(contactId) && t.status === 'Active').length;
  };

  return (
    <div style={{ background: '#111827', color: '#f3f4f6', minHeight: '100vh', padding: '24px' }}>
      <h1 style={{ fontSize: '24px', fontWeight: 'bold', marginBottom: '24px' }}>Member Workload</h1>
      
      <button
        onClick={loadData}
        style={{
          background: '#3b82f6',
          color: 'white',
          padding: '8px 16px',
          borderRadius: '6px',
          border: 'none',
          cursor: 'pointer',
          marginBottom: '24px',
        }}
      >
        Refresh
      </button>

      {loading ? (
        <div>Loading...</div>
      ) : (
        <div style={{ display: 'grid', gap: '12px' }}>
          {contacts.slice(0, 20).map(contact => {
            const workload = getWorkload(contact.id);
            return (
              <div
                key={contact.id}
                style={{
                  background: '#1f2937',
                  padding: '16px',
                  borderRadius: '6px',
                  border: '1px solid #374151',
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                }}
              >
                <div>
                  <div style={{ fontWeight: '600' }}>
                    {contact.firstName} {contact.lastName}
                  </div>
                  <div style={{ fontSize: '12px', color: '#9ca3af' }}>
                    {contact.profiles?.[0]?.email}
                  </div>
                </div>
                <div style={{
                  background: workload > 10 ? '#ef4444' : workload > 5 ? '#f59e0b' : '#10b981',
                  color: 'white',
                  padding: '8px 16px',
                  borderRadius: '6px',
                  fontWeight: 'bold',
                }}>
                  {workload} tasks
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
