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

export default function EmployeeDashboard() {
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [stats, setStats] = useState({
    total: 0,
    active: 0,
    newHires: 0,
    departments: [] as Array<{ name: string; count: number }>
  });

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

  const loadData = async () => {
    try {
      setLoading(true);
      const response = await (window as any).mcp?.callTool('rippling_list_employees', { limit: 500 });
      
      if (response?.employees) {
        setData(response);
        calculateStats(response.employees);
      } else {
        setData(getSampleData());
        calculateStats(getSampleData().employees);
      }
    } catch (err) {
      console.error('Error loading employees:', err);
      setError(err instanceof Error ? err.message : 'Failed to load employees');
      const sample = getSampleData();
      setData(sample);
      calculateStats(sample.employees);
    } finally {
      setLoading(false);
    }
  };

  const calculateStats = (employees: any[]) => {
    const active = employees.filter(e => e.status === 'ACTIVE').length;
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    const newHires = employees.filter(e => 
      e.startDate && new Date(e.startDate) > thirtyDaysAgo
    ).length;

    const deptMap = new Map<string, number>();
    employees.forEach(e => {
      const dept = e.department || 'Unassigned';
      deptMap.set(dept, (deptMap.get(dept) || 0) + 1);
    });

    const departments = Array.from(deptMap.entries())
      .map(([name, count]) => ({ name, count }))
      .sort((a, b) => b.count - a.count);

    setStats({
      total: employees.length,
      active,
      newHires,
      departments
    });
  };

  const getSampleData = () => {
    return {
      employees: [
        { id: '1', firstName: 'John', lastName: 'Doe', status: 'ACTIVE', department: 'Engineering', startDate: '2024-01-15' },
        { id: '2', firstName: 'Jane', lastName: 'Smith', status: 'ACTIVE', department: 'Engineering', startDate: '2023-05-20' },
        { id: '3', firstName: 'Bob', lastName: 'Johnson', status: 'ACTIVE', department: 'Sales', startDate: '2024-02-01' },
      ]
    };
  };

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

  return (
    <div className="container">
      <div className="header">
        <h1>Employee Dashboard</h1>
        <p className="subtitle">Company headcount and overview</p>
      </div>
      
      {error && <div className="error">{error}</div>}
      
      <div className="stats-grid">
        <div className="stat-card stat-primary">
          <div className="stat-value">{stats.total}</div>
          <div className="stat-label">Total Employees</div>
        </div>
        <div className="stat-card stat-success">
          <div className="stat-value">{stats.active}</div>
          <div className="stat-label">Active</div>
        </div>
        <div className="stat-card stat-info">
          <div className="stat-value">{stats.newHires}</div>
          <div className="stat-label">New Hires (30d)</div>
        </div>
        <div className="stat-card stat-warning">
          <div className="stat-value">{stats.total - stats.active}</div>
          <div className="stat-label">Inactive</div>
        </div>
      </div>

      <div className="card">
        <h2>Employees by Department</h2>
        <div className="dept-list">
          {stats.departments.map((dept, idx) => (
            <div key={idx} className="dept-item">
              <span className="dept-name">{dept.name}</span>
              <span className="dept-count">{dept.count}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
