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

export default function TimeDashboard() {
  const [timelogs, setTimelogs] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

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

  const loadTimelogs = async () => {
    setLoading(true);
    try {
      const result = await window.mcp.callTool('wrike_list_timelogs', {});
      setTimelogs(result.timelogs || []);
    } catch (error) {
      console.error('Failed to load timelogs:', error);
    } finally {
      setLoading(false);
    }
  };

  const totalHours = timelogs.reduce((sum, log) => sum + log.hours, 0);

  return (
    <div style={{ background: '#111827', color: '#f3f4f6', minHeight: '100vh', padding: '24px' }}>
      <h1 style={{ fontSize: '24px', fontWeight: 'bold', marginBottom: '24px' }}>Time Dashboard</h1>
      
      <div style={{ 
        background: '#1f2937', 
        padding: '24px', 
        borderRadius: '8px', 
        marginBottom: '24px',
        border: '1px solid #374151'
      }}>
        <div style={{ fontSize: '36px', fontWeight: 'bold', color: '#3b82f6' }}>
          {totalHours.toFixed(2)} hrs
        </div>
        <div style={{ color: '#9ca3af' }}>Total Logged Time</div>
      </div>

      <button
        onClick={loadTimelogs}
        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' }}>
          {timelogs.map(log => (
            <div
              key={log.id}
              style={{
                background: '#1f2937',
                padding: '12px',
                borderRadius: '6px',
                border: '1px solid #374151',
                display: 'flex',
                justifyContent: 'space-between',
              }}
            >
              <div>
                <div style={{ fontWeight: '600' }}>{log.hours}h</div>
                <div style={{ fontSize: '12px', color: '#9ca3af' }}>
                  {new Date(log.trackedDate).toLocaleDateString()}
                </div>
              </div>
              {log.comment && (
                <div style={{ fontSize: '14px', color: '#9ca3af' }}>{log.comment}</div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
