import { useState, useEffect } from 'react';
import './styles.css';

export default function TimeTracker() {
  const [entries, setEntries] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

  const loadEntries = async () => {
    try {
      setLoading(true);
      const response = await (window as any).mcp?.callTool('rippling_list_time_entries', { limit: 100 });
      
      if (response?.entries) {
        setEntries(response.entries);
      } else {
        setEntries(getSampleEntries());
      }
    } catch (err) {
      console.error('Error:', err);
      setError(err instanceof Error ? err.message : 'Failed to load');
      setEntries(getSampleEntries());
    } finally {
      setLoading(false);
    }
  };

  const getSampleEntries = () => [
    { id: '1', employee: 'John Doe', date: '2024-02-12', hours: 8, project: 'Project A', status: 'APPROVED' },
    { id: '2', employee: 'Jane Smith', date: '2024-02-12', hours: 7.5, project: 'Project B', status: 'PENDING' },
    { id: '3', employee: 'Bob Johnson', date: '2024-02-11', hours: 8, project: 'Project A', status: 'APPROVED' },
  ];

  const totalHours = entries.reduce((sum, e) => sum + (e.hours || 0), 0);

  if (loading) {
    return <div className="container"><div className="loading">Loading time entries...</div></div>;
  }

  return (
    <div className="container">
      <div className="header">
        <h1>Time Tracker</h1>
        <p className="subtitle">{entries.length} entries • {totalHours.toFixed(1)} total hours</p>
      </div>

      {error && <div className="error">{error}</div>}

      <div className="card">
        <h2>Recent Time Entries</h2>
        <table className="time-table">
          <thead>
            <tr>
              <th>Employee</th>
              <th>Date</th>
              <th>Hours</th>
              <th>Project</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            {entries.map(entry => (
              <tr key={entry.id}>
                <td>{entry.employee}</td>
                <td>{entry.date}</td>
                <td className="hours">{entry.hours}</td>
                <td>{entry.project}</td>
                <td><span className={`badge status-${entry.status.toLowerCase()}`}>{entry.status}</span></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
