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

export default function EmployeeDirectory() {
  const [employees, setEmployees] = useState<any[]>([]);
  const [filteredEmployees, setFilteredEmployees] = useState<any[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [departmentFilter, setDepartmentFilter] = useState('all');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

  useEffect(() => {
    filterEmployees();
  }, [searchTerm, departmentFilter, employees]);

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

  const filterEmployees = () => {
    let filtered = [...employees];

    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      filtered = filtered.filter(emp => 
        emp.firstName?.toLowerCase().includes(term) ||
        emp.lastName?.toLowerCase().includes(term) ||
        emp.email?.toLowerCase().includes(term) ||
        emp.title?.toLowerCase().includes(term)
      );
    }

    if (departmentFilter !== 'all') {
      filtered = filtered.filter(emp => emp.department === departmentFilter);
    }

    setFilteredEmployees(filtered);
  };

  const getDepartments = () => {
    const depts = new Set(employees.map(e => e.department).filter(Boolean));
    return Array.from(depts).sort();
  };

  const getSampleEmployees = () => [
    { id: '1', firstName: 'John', lastName: 'Doe', email: 'john@company.com', title: 'Engineer', department: 'Engineering', status: 'ACTIVE' },
    { id: '2', firstName: 'Jane', lastName: 'Smith', email: 'jane@company.com', title: 'Manager', department: 'Sales', status: 'ACTIVE' },
    { id: '3', firstName: 'Bob', lastName: 'Johnson', email: 'bob@company.com', title: 'Designer', department: 'Design', status: 'ACTIVE' },
    { id: '4', firstName: 'Alice', lastName: 'Williams', email: 'alice@company.com', title: 'Analyst', department: 'Finance', status: 'ACTIVE' },
  ];

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

  return (
    <div className="container">
      <div className="header">
        <h1>Employee Directory</h1>
        <p className="subtitle">{filteredEmployees.length} employees</p>
      </div>

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

      <div className="filters">
        <input
          type="text"
          placeholder="Search by name, email, or title..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="search-input"
        />
        <select
          value={departmentFilter}
          onChange={(e) => setDepartmentFilter(e.target.value)}
          className="filter-select"
        >
          <option value="all">All Departments</option>
          {getDepartments().map(dept => (
            <option key={dept} value={dept}>{dept}</option>
          ))}
        </select>
      </div>

      <div className="employee-grid">
        {filteredEmployees.map(emp => (
          <div key={emp.id} className="employee-card">
            <div className="emp-avatar">
              {emp.firstName?.[0]}{emp.lastName?.[0]}
            </div>
            <div className="emp-info">
              <h3>{emp.firstName} {emp.lastName}</h3>
              <p className="emp-title">{emp.title || 'N/A'}</p>
              <p className="emp-dept">{emp.department || 'Unassigned'}</p>
              <p className="emp-email">{emp.email}</p>
            </div>
            <span className={`emp-status status-${emp.status?.toLowerCase()}`}>
              {emp.status}
            </span>
          </div>
        ))}
      </div>

      {filteredEmployees.length === 0 && (
        <div className="empty-state">No employees found matching your criteria</div>
      )}
    </div>
  );
}
