import React, { useState, useMemo, useTransition } from 'react';

const useDebounce = <T,>(value: T, delay: number): T => {
  const [debouncedValue, setDebouncedValue] = useState(value);
  React.useEffect(() => {
    const handler = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(handler);
  }, [value, delay]);
  return debouncedValue;
};

const useToast = () => {
  const [toast, setToast] = useState<string | null>(null);
  const showToast = (message: string) => {
    setToast(message);
    setTimeout(() => setToast(null), 3000);
  };
  return { toast, showToast };
};

const mockEmployees = [
  { id: 'EMP001', name: 'Sarah Johnson', position: 'CEO', email: 'sarah@company.com', phone: '555-0201', status: 'active' },
  { id: 'EMP002', name: 'Michael Chen', position: 'CTO', email: 'michael@company.com', phone: '555-0202', status: 'active' },
  { id: 'EMP003', name: 'Emily Rodriguez', position: 'Sales Manager', email: 'emily@company.com', phone: '555-0203', status: 'active' },
  { id: 'EMP004', name: 'David Kim', position: 'Software Engineer', email: 'david@company.com', phone: '555-0204', status: 'active' },
  { id: 'EMP005', name: 'Lisa Martinez', position: 'Marketing Director', email: 'lisa@company.com', phone: '555-0205', status: 'on-leave' },
  { id: 'EMP006', name: 'John Smith', position: 'Accountant', email: 'john@company.com', phone: '555-0206', status: 'active' },
];

const App: React.FC = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [isPending, startTransition] = useTransition();
  const { toast, showToast } = useToast();
  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredEmployees = useMemo(() => {
    return mockEmployees.filter((emp) => {
      const matchesSearch = emp.name.toLowerCase().includes(debouncedSearch.toLowerCase()) || emp.position.toLowerCase().includes(debouncedSearch.toLowerCase()) || emp.id.includes(debouncedSearch);
      const matchesFilter = filterStatus === 'all' || emp.status === filterStatus;
      return matchesSearch && matchesFilter;
    });
  }, [debouncedSearch, filterStatus]);

  const stats = useMemo(() => {
    const total = mockEmployees.length;
    const active = mockEmployees.filter(e => e.status === 'active').length;
    const onLeave = mockEmployees.filter(e => e.status === 'on-leave').length;
    return { total, active, onLeave };
  }, []);

  const handleFilterChange = (status: string) => {
    startTransition(() => {
      setFilterStatus(status);
      showToast(`Filter: ${status === 'all' ? 'All Employees' : status === 'on-leave' ? 'On Leave' : 'Active'}`);
    });
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Employee Directory</h1>
        <p>Employee list and contact details</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Employees</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card stat-success">
          <div className="stat-label">Active</div>
          <div className="stat-value">{stats.active}</div>
        </div>
        <div className="stat-card stat-warning">
          <div className="stat-label">On Leave</div>
          <div className="stat-value">{stats.onLeave}</div>
        </div>
      </div>

      <div className="controls">
        <input type="text" className="search-input" placeholder="Search by name, position, or ID..." value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} />
        <div className="filter-buttons">
          {['all', 'active', 'on-leave'].map((status) => (
            <button key={status} className={`filter-btn ${filterStatus === status ? 'active' : ''}`} onClick={() => handleFilterChange(status)}>
              {status === 'all' ? 'All' : status === 'on-leave' ? 'On Leave' : 'Active'}
            </button>
          ))}
        </div>
      </div>

      {filteredEmployees.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">👤</div>
          <h3>No employees found</h3>
          <p>Try adjusting your search or filters</p>
        </div>
      ) : (
        <div className={`data-grid ${isPending ? 'loading' : ''}`}>
          <table>
            <thead>
              <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Position</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {filteredEmployees.map((emp) => (
                <tr key={emp.id}>
                  <td style={{ fontFamily: 'monospace', color: 'var(--accent-primary)', fontWeight: 600 }}>{emp.id}</td>
                  <td style={{ fontWeight: 500 }}>{emp.name}</td>
                  <td>{emp.position}</td>
                  <td>{emp.email}</td>
                  <td>{emp.phone}</td>
                  <td>
                    <span style={{ display: 'inline-block', padding: '0.375rem 0.75rem', borderRadius: '9999px', fontSize: '0.75rem', fontWeight: 600, background: emp.status === 'active' ? 'rgba(16, 185, 129, 0.1)' : 'rgba(245, 158, 11, 0.1)', color: emp.status === 'active' ? 'var(--success)' : 'var(--warning)' }}>
                      {emp.status === 'on-leave' ? 'On Leave' : 'Active'}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {toast && <div className="toast">{toast}</div>}
    </div>
  );
};

export default App;
