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 mockTimeActivities = [
  { id: 'TA001', employee: 'David Kim', customer: 'Acme Corp', date: '2024-01-15', hours: 8.0, billable: true, rate: 150.00 },
  { id: 'TA002', employee: 'Emily Rodriguez', customer: 'Tech Solutions Inc', date: '2024-01-16', hours: 6.5, billable: true, rate: 175.00 },
  { id: 'TA003', employee: 'Lisa Martinez', customer: 'Internal - Marketing', date: '2024-01-16', hours: 4.0, billable: false, rate: 0 },
  { id: 'TA004', employee: 'David Kim', customer: 'Global Enterprises', date: '2024-01-17', hours: 7.0, billable: true, rate: 150.00 },
  { id: 'TA005', employee: 'John Smith', customer: 'Startup LLC', date: '2024-01-18', hours: 5.5, billable: true, rate: 125.00 },
  { id: 'TA006', employee: 'Emily Rodriguez', customer: 'Internal - Training', date: '2024-01-18', hours: 3.0, billable: false, rate: 0 },
];

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

  const filteredActivities = useMemo(() => {
    return mockTimeActivities.filter((activity) => {
      const matchesSearch = activity.employee.toLowerCase().includes(debouncedSearch.toLowerCase()) || activity.customer.toLowerCase().includes(debouncedSearch.toLowerCase()) || activity.id.includes(debouncedSearch);
      const matchesFilter = filterBillable === 'all' || (filterBillable === 'billable' && activity.billable) || (filterBillable === 'non-billable' && !activity.billable);
      return matchesSearch && matchesFilter;
    });
  }, [debouncedSearch, filterBillable]);

  const stats = useMemo(() => {
    const totalHours = mockTimeActivities.reduce((s, a) => s + a.hours, 0);
    const billableHours = mockTimeActivities.filter(a => a.billable).reduce((s, a) => s + a.hours, 0);
    const nonBillableHours = mockTimeActivities.filter(a => !a.billable).reduce((s, a) => s + a.hours, 0);
    const totalRevenue = mockTimeActivities.reduce((s, a) => s + (a.hours * a.rate), 0);
    return { totalHours, billableHours, nonBillableHours, totalRevenue };
  }, []);

  const handleFilterChange = (filter: string) => {
    startTransition(() => {
      setFilterBillable(filter);
      showToast(`Filter: ${filter === 'all' ? 'All' : filter === 'billable' ? 'Billable' : 'Non-Billable'}`);
    });
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Time Tracking</h1>
        <p>Time activities and billable hours</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Hours</div>
          <div className="stat-value">{stats.totalHours.toFixed(1)}</div>
        </div>
        <div className="stat-card stat-success">
          <div className="stat-label">Billable Hours</div>
          <div className="stat-value">{stats.billableHours.toFixed(1)}</div>
        </div>
        <div className="stat-card stat-warning">
          <div className="stat-label">Non-Billable Hours</div>
          <div className="stat-value">{stats.nonBillableHours.toFixed(1)}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Revenue</div>
          <div className="stat-value">${stats.totalRevenue.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
      </div>

      <div className="controls">
        <input type="text" className="search-input" placeholder="Search by employee, customer, or ID..." value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} />
        <div className="filter-buttons">
          {['all', 'billable', 'non-billable'].map((filter) => (
            <button key={filter} className={`filter-btn ${filterBillable === filter ? 'active' : ''}`} onClick={() => handleFilterChange(filter)}>
              {filter === 'all' ? 'All' : filter === 'billable' ? 'Billable' : 'Non-Billable'}
            </button>
          ))}
        </div>
      </div>

      {filteredActivities.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">⏰</div>
          <h3>No time activities found</h3>
          <p>Try adjusting your search or filters</p>
        </div>
      ) : (
        <div className={`data-grid ${isPending ? 'loading' : ''}`}>
          <table>
            <thead>
              <tr>
                <th>ID</th>
                <th>Employee</th>
                <th>Customer</th>
                <th>Date</th>
                <th>Hours</th>
                <th>Rate</th>
                <th>Total</th>
              </tr>
            </thead>
            <tbody>
              {filteredActivities.map((activity) => (
                <tr key={activity.id}>
                  <td style={{ fontFamily: 'monospace', color: 'var(--accent-primary)', fontWeight: 600 }}>{activity.id}</td>
                  <td style={{ fontWeight: 500 }}>{activity.employee}</td>
                  <td>{activity.customer}</td>
                  <td>{activity.date}</td>
                  <td>{activity.hours.toFixed(1)}</td>
                  <td className="amount">${activity.rate.toFixed(2)}</td>
                  <td className="amount">${(activity.hours * activity.rate).toFixed(2)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

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

export default App;
